2016-06-21 75 views
0

我有两个具有一对多关系的“父”和“子”表。MySQL:在父表中选择在子表中有两行的行(一对多)

我想从“父”表谁在抢行的所有记录“子”表有状态“挂起”和“批准”

例如 “制造商”表:

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

嘿,等等:-)你迷惑大家: - )一方面'status(int)'在其他''待定','失败','批准',那么你的'status'列的类型是什么? – Alex

回答

0

您可以使用以下查询来获取的那些涉及到两个status15厂商的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 ...) 
+0

'..status in(1,5)...' – 1000111

+0

@ 1000111是的,你说得对,我已经纠正了我的答案。 –

0
select distinct man.name from manufacturers man, models mod 
where man.id = mod.manufacturer_id 
and mod.status in ('pending', 'approved') 
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不再被诠释,您可以:

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 
相关问题