SQL 仅显示包含这两项的结果
SQL show only results that have both items
我有一个 SQL table 上面有人们吃的名字和水果。
我只希望结果显示同时吃苹果和香蕉的人的名字。但是如果我使用“Where Item='Banana' and item='Apple',数据什么都不显示。
如果我使用:Where item in('banana','apple'),它显示的结果如 table.
中所示
Name
Item
John
Apple
David
Banana
John
Banana
您可以使用 DISTINCT
和 EXISTS
子句来获得您需要的内容。
SELECT DISTINCT name
FROM table1 a
WHERE a.Item = 'Apple'
AND EXISTS (SELECT *
FROM table1 b
WHERE b.Item = 'Banana'
AND b.Name = a.Name)
WITH CTE_Apple AS
(
SELECT * FROM Table where Item = 'Apple'
)
,
CTE_Banana AS
(
SELECT * FROM Table WHERE Item = 'Banana'
)
SELECT
A.Name
FROM
CTE_Apple AS A
JOIN
CTE_Banana AS B ON B.Name = A.Name
基本上创建两个 sub-sets 数据并在数据相交的地方将它们连接在一起。还有很多其他方法可以做到这一点,但我发现 CTE(通用 Table 表达式)最优雅
使用子查询应该适用于任何 RDBMS:
select distinct Name
from table_name
where Item = 'Apple'
and Name in
(select Name from table_name where Item = 'Banana');
我们可以做一个 GROUP BY 然后 select 只吃列表中 2 个水果的人,即他们两个
CREATE TABLE eaten(
person VARCHAR (10),
fruit VARCHAR (10));
INSERT INTO eaten VALUES
('John','apple'),
('Bill','apple'),
('Bill','pear'),
('David','banana'),
('David','banana'),
('John','banana');
SELECT person
FROM eaten
WHERE fruit IN ('apple','banana')
GROUP BY person
HAVING COUNT(DISTINCT fruit) =2;
| person |
| :----- |
| John |
db<>fiddle here
我有一个 SQL table 上面有人们吃的名字和水果。 我只希望结果显示同时吃苹果和香蕉的人的名字。但是如果我使用“Where Item='Banana' and item='Apple',数据什么都不显示。 如果我使用:Where item in('banana','apple'),它显示的结果如 table.
中所示Name | Item |
---|---|
John | Apple |
David | Banana |
John | Banana |
您可以使用 DISTINCT
和 EXISTS
子句来获得您需要的内容。
SELECT DISTINCT name
FROM table1 a
WHERE a.Item = 'Apple'
AND EXISTS (SELECT *
FROM table1 b
WHERE b.Item = 'Banana'
AND b.Name = a.Name)
WITH CTE_Apple AS
(
SELECT * FROM Table where Item = 'Apple'
)
,
CTE_Banana AS
(
SELECT * FROM Table WHERE Item = 'Banana'
)
SELECT
A.Name
FROM
CTE_Apple AS A
JOIN
CTE_Banana AS B ON B.Name = A.Name
基本上创建两个 sub-sets 数据并在数据相交的地方将它们连接在一起。还有很多其他方法可以做到这一点,但我发现 CTE(通用 Table 表达式)最优雅
使用子查询应该适用于任何 RDBMS:
select distinct Name
from table_name
where Item = 'Apple'
and Name in
(select Name from table_name where Item = 'Banana');
我们可以做一个 GROUP BY 然后 select 只吃列表中 2 个水果的人,即他们两个
CREATE TABLE eaten( person VARCHAR (10), fruit VARCHAR (10));
INSERT INTO eaten VALUES ('John','apple'), ('Bill','apple'), ('Bill','pear'), ('David','banana'), ('David','banana'), ('John','banana');
SELECT person FROM eaten WHERE fruit IN ('apple','banana') GROUP BY person HAVING COUNT(DISTINCT fruit) =2;
| person | | :----- | | John |
db<>fiddle here