2013-10-21 19 views
-2

Staff简单但不可能单MYSQL一对多查询

ID Name Gender 
1 John Male 
2 Adam Male 
3 Joella Female 

Food

ID StaffID Name 
1 1  Eggs 
2 1  Bacon 
3 1  Toast 
4 2  Eggs 
5 2  Bacon 
6 3  Toast 

我需要谁消耗了两个鸡蛋和烤面包的男性工作人员的名字。
答案应该是John,但每次我使用AND子句时,它都是零结果,因为它正在查看相同的“行字段”。使用OR返回不正确的结果。

我试过左连接,标准连接和其他几个。

SELECT field from table left join table2 on table.field=table2.field 
where field ='eggs' && field = 'toast' && gender = 'male' 

这个技巧是我试图在单个查询中做到这一点。

+0

我认为你应该在你的查询中使用AND代替&。 – Maximus2012

+0

在table2.field中你是通过id还是staffid加入的? – Mihai

回答

3

field不能eggstoast在同一时间,所以加入对同桌再次

SELECT field from table left join table2 ON table.field = table2.field 
left join table2 table22 ON table.field = table22.field 
WHERE table2.field = 'eggs' AND table22.field = 'toast' && gender = 'male' 

我也敢肯定,你不想加入ON“场”,但像staffID这样的其他专栏。组由

+3

+1但是不要使用左连接。这是一个内部联接。 –

+0

@BillKarwin你绝对是对的;在这种情况下无需使用“LEFT JOIN”(无论如何都无效) –

+0

谢谢!像魅力一样工作。我从来不必在查询中对同一张桌子进行第二次连接。第一次为一切! – Kauffju3

2

职员,然后筛选所得基团为那些满足所期望的标准:

SELECT Staff.Name 
FROM  Staff JOIN Food ON Food.StaffID = Staff.ID 
WHERE Food.Name IN ('Eggs', 'Toast') 
    AND Staff.Gender = 'Male' 
GROUP BY Staff.ID 
HAVING COUNT(Food.ID) = 2 
2
SELECT name, count(Food.id) AS foodcount 
FROM Staff 
LEFT JOIN Food ON Staff.id = Food.StaffID 
WHERE Food.Name IN ('eggs', 'toast') AND gender = 'male' 
GROUP BY Staff.id 
HAVING foodcount = 2; 
+0

在鸡蛋或烤面包被复制而不是每个鸡蛋或烤面包之一的情况下,你不想数数不同吗? – Taryn

+0

OP从来没有说如果'food.id,food.staffid'是一个独特的元组或不。如果不是的话,那么数(不同的)就会有意义。 –

1

可以用JOIN语法去,或者与IN语法

SELECT name from staf 
where 
ID in (select StaffId from food where Name='egg') and 
ID in (select StaffId from food where Name='toast') and 
gender = 'male' 
0
select s.name from staff_table s join food_table f1 on f1.staff_id=s.id join food_table f2 on f2.staff_id=s.id where f1.name='Toast' and f2.name='Eggs' and s.gender='Male'