-2

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

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

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

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

诀窍是我试图在单个查询中执行此操作。

4

5 回答 5

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“字段”,而是加入其他一些列,如人员 ID。

于 2013-10-21T21:01:12.137 回答
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
于 2013-10-21T21:02:26.497 回答
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;
于 2013-10-21T21:02:53.123 回答
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'
于 2013-10-21T21:03:59.373 回答
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'
于 2013-10-21T21:32:10.687 回答