我有两个表“父”和“孩子”,有一对多的关系。
我希望从“父”表中获取所有记录,其中“子”表中的行的状态为“待定”和“已批准”
e.g。 “制造商”表:
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”,因为在“模型”中Boots的状态为“pending”(id = 1)和“approved”(id = 5)
答案 0 :(得分:0)
您可以使用以下查询来获取与status
,1
和5
相关的制造商的ID:
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 ...)
答案 1 :(得分:0)
select distinct man.name from manufacturers man, models mod
where man.id = mod.manufacturer_id
and mod.status in ('pending', 'approved')
答案 2 :(得分:0)
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
更新我不知道你为什么更改了你的OP,但是如果你的status
不再是int,你可以:
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))=2