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

时间:2013-10-21 20:58:50

标签: mysql database select join relational-division

Staff

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

我需要MALE工作人员的名字,他已经吃过鸡蛋和烤面包。
答案应该是John,但每次我使用AND子句时都是零结果,因为它看着同一行领域”。使用OR返回不正确的结果。

我尝试了左连接,标准连接和其他一些。

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

这方面的诀窍是我试图在一个查询中执行此操作。

5 个答案:

答案 0 :(得分: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。

答案 1 :(得分: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 :(得分: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;

答案 3 :(得分: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'

答案 4 :(得分: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'