我有两个表"parent“和"child”,具有一对多的关系。
我希望从“父”表中抓取“子”表中行状态为“pending”和“approved”的所有记录
例如“制造商”表:
id, name
1, Boots
2, Audi
3, AVG“型号”表:
id, manufacturer_id, status (int)
1, 1, pending
2, 1, failed
3, 1, approved
4, 2, failed
5, 3, approved我想要抓取所有拥有状态为“待处理”和“已批准”的型号的制造商。给定上述数据,mysql应该返回" Boots“,因为在"models”中,Boot有一个状态为"pending“(id = 1)和"approved”(id = 5)的记录
发布于 2016-06-21 20:53:29
您可以使用以下查询来获取与status、1和5相关的制造商的ids
SELECT manufacturer_id
FROM models
WHERE status IN (1,5)
GROUP BY manufacturer_id
HAVING COUNT(DISTINCT status) = 2现在,您可以使用上面的查询作为子查询,以获得预期的结果集:
SELECT *
FROM manufacturers
WHERE id IN ( ... above query here ...)发布于 2016-06-21 21:01:49
select distinct man.name from manufacturers man, models mod
where man.id = mod.manufacturer_id
and mod.status in ('pending', 'approved')发布于 2016-06-21 21:04:49
http://sqlfiddle.com/#!9/9c1e32/3
SELECT m.*
FROM manufacturers m
JOIN models
ON m.id = models.manufacturer_id
GROUP BY m.id
HAVING MAX(IF(models.status=1,1,0))+MAX(IF(models.status=2,1,0))=2更新我不知道你为什么改变你的操作,但是如果你的status不再是整数,你可以:
SELECT m.*
FROM manufacturers m
JOIN models
ON m.id = models.manufacturer_id
GROUP BY m.id
HAVING MAX(IF(models.status='pending',1,0))+MAX(IF(models.status='approved',1,0))=2https://stackoverflow.com/questions/37944948
复制相似问题