2016-06-21 78 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 
相關問題