我想根据两个条件选择父母:父母是否有活跃的孩子或根本没有孩子。下面介绍第一个:
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;
如何添加第二个条件?
我想根据两个条件选择父母:父母是否有活跃的孩子或根本没有孩子。下面介绍第一个:
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;
如何添加第二个条件?
尝试:
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;
尝试这样的事情
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;
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;