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 Iphone
或 combination 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
如果您需要的名称至少包含 Iphone
或 Samsung 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 ) ;
这是另一个解决方案:
SELECT name, GROUP_CONCAT(DISTINCT brand ORDER BY brand) AS brands
FROM mytable
GROUP BY name
HAVING brands IN ('Iphone', 'Iphone,Samsung');
我有以下架构:
+--------+---------+
|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 Iphone
或 combination 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
如果您需要的名称至少包含 Iphone
或 Samsung 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 ) ;
这是另一个解决方案:
SELECT name, GROUP_CONCAT(DISTINCT brand ORDER BY brand) AS brands
FROM mytable
GROUP BY name
HAVING brands IN ('Iphone', 'Iphone,Samsung');