SQL 带 OR 条件的子查询

SQL Subquery with OR condition

我有以下架构:

+--------+---------+
|Name    |    Brand|
+--------+---------|
|John    |   Iphone|
|John    |  Samsung|
|Carl    |   Xiaomi|
|Natan   |   Iphone|
|Julie   |  Samsung|
+--------+---------+

在我的结果中,我需要 return 在这 2 个场景中框架的名称:

1-只有Iphone

2 - 拥有独家组合Iphone和三星;这样,我需要这个输出:

+--------+
|Name    |
+--------+
|John    |
|Natan   |
+--------+

这是我尝试过的方法,但没有成功:

select name
from schema
where brand = 'Iphone' or
brand in 
    (select brand
    from schema
    where brand = 'Iphone' and brand = 'Samsung')

您可以尝试在 iphone olny 和对 iphone-samsung

之间使用联合
    select name
    from schema
    where brand = 'Iphone' 
    union 
    select name 
    from schema
    where brand in  ('Iphone' , 'Samsung') 
    group by name
    having count(distinct brand) = 2

编辑:如果您希望名称为 only have Iphonecombination of Iphone and Samsung:

的组合

尝试:

SELECT distinct name
FROM my_table
WHERE Brand IN (
               SELECT Brand
               FROM my_table
               WHERE brand='Iphone'
               GROUP BY Brand
               HAVING COUNT(*) = 1
                )
 OR   name in ( SELECT name
                FROM my_table
                WHERE brand in ('Iphone','Samsung')
                GROUP BY name
                 HAVING COUNT(brand)=2 
              ) 
; 

演示:https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/150

如果您需要的名称至少包含 IphoneSamsung and Iphone 的组合,请使用:

 select distinct name
 from my_table
 where brand = 'Iphone' or name in ( SELECT name
                                    FROM my_table
                                    WHERE brand in ('Iphone','Samsung')
                                    GROUP BY name
                                    HAVING COUNT(brand)=2 ) ;
                                 

演示:https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/148

这是另一个解决方案:

SELECT name, GROUP_CONCAT(DISTINCT brand ORDER BY brand) AS brands
FROM mytable
GROUP BY name
HAVING brands IN ('Iphone', 'Iphone,Samsung');