只有在没有孩子的情况下加入?

时间:2013-05-28 09:13:25

标签: mysql

我想根据两个条件选择一个父母:如果父母有一个活跃的孩子或根本没有孩子。以下内容涵盖第一个:

SELECT p.* FROM parents p, children c 
WHERE p.status = 'active' 
AND c.parent_id = p.id AND c.status = 'active' 
ORDER BY RAND() LIMIT 1;

如何添加第二个条件?

3 个答案:

答案 0 :(得分:2)

尝试:

SELECT p.* FROM parents p
LEFT JOIN children c
ON children.parent_id = parent.id and children.status <> 'active' 
WHERE parent.status = 'active' AND children.parent_id is null
ORDER BY RAND() LIMIT 1;

答案 1 :(得分:0)

尝试这样的事情

SELECT p.* 
FROM parents p, children c 
WHERE p.status = 'active' 
AND c.parent_id = p.id AND c.status = 'active' 
union
SELECT p.* 
FROM parents p
where p.id not in (select distinct c.parent_id from children)
ORDER BY RAND() LIMIT 1;

答案 2 :(得分:0)

SELECT * FROM parents
LEFT JOIN children 
ON children.parent_id = parent.id AND children.status = 'active' 
WHERE parent.status = 'active'
ORDER BY RAND() LIMIT 1;