【问题标题】:select persons who like apple and banana both选择同时喜欢苹果和香蕉的人
【发布时间】:2015-02-21 09:04:21
【问题描述】:

如何从下面的数据中选择像苹果和香蕉这样的人?

表:我的表

persons |  fruit
-----------------------------
   P1       Apple
   P1       Banana
   P1       Mango
   P2       Banana
   P2       Apple
   P3       Mango   
   P3       Apple  

即在这种情况下,P1,P2 应该是结果。

我试过了

select * from MyTable where fruit in("Apple","Banana");

这也是 P3 的结果,因为 P3 也有苹果。

感谢您的帮助。

【问题讨论】:

  • group by persons having count(*) = 2
  • 其结果 P1,Apple
  • 请注意,虽然进行分组并选择另一列并不能保证它将返回哪个值,但在您的情况下它将返回 2 个人 p1 和 p2 但可能是因为您选择 * 它最终会在水果列中显示苹果。如果你想同时获得显示使用group_concat

标签: mysql sql select group-by having


【解决方案1】:
SELECT a.persons 
FROM MyTable a JOIN MyTable b on a.persons=b.persons 
WHERE a.fruit='Apple' and b.fruit='Banana'

【讨论】:

    【解决方案2】:

    这可行:

    SELECT distinct `t1`.`persons` FROM MyTable AS `t1`
    INNER JOIN MyTable AS `t2` ON `t1`.`persons` = `t2`.`persons`
    WHERE `t1`.`fruit` = 'Banana' AND `t2`.`fruit` = 'Apple'
    

    【讨论】:

      【解决方案3】:

      试试这个:

      SELECT persons 
      FROM MyTable 
      WHERE fruit IN ('Apple', 'Banana')
      GROUP BY persons
      HAVING COUNT(DISTINCT fruit) = 2;
      

      【讨论】:

      • 其结果 P1,Apple @Saharsh
      【解决方案4】:
      select * from MyTable where fruit in("Apple") and persons in(select persons from MyTable where fruit in("Banana");
      

      【讨论】:

        【解决方案5】:

        试试这个:

        select persons from MyTable where fruit in("Apple","Banana");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-07-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-13
          相关资源
          最近更新 更多