【问题标题】:Simple but Impossible single MYSQL One to Many Query简单但不可能的单个 MYSQL 一对多查询
【发布时间】:2013-10-21 20:58:49
【问题描述】:

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'

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

【问题讨论】:

  • 我认为您应该在查询中使用 AND 代替 &&。
  • 在table2.field中你是通过id还是staffid加入的?

标签: mysql database select join relational-division


【解决方案1】:

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。

【讨论】:

  • @BillKarwin 你说得对;在这种情况下不需要LEFT JOIN(无论如何它都无效)
  • 谢谢!像魅力一样工作。我从来不需要在查询中对同一个表进行第二次连接。一切都是第一次!
【解决方案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

【讨论】:

    【解决方案3】:
    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;
    

    【讨论】:

    • 如果鸡蛋或吐司被重复而不是一个一个,你不想计数不同吗?
    • OP 从未说过 food.id,food.staffid 是否是唯一的元组。如果不是,那么是的,count(distinct) 是有意义的。
    【解决方案4】:

    你可以使用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'
    

    【讨论】:

      【解决方案5】:
      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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-09
        • 1970-01-01
        • 1970-01-01
        • 2014-04-06
        相关资源
        最近更新 更多