鉴于下表:
Column1 | Column2
10 | 200
10 | 201
11 | 100
11 | 200
11 | 300
12 | 200
13 | 100
13 | 200
13 | 201
13 | 300
我希望提取列2包含每个唯一column1的值200和201的所有行。输出应为:
10 | 200
10 | 201
13 | 200
13 | 201
该表包含大约800万行,我能想出的所有内容都很慢。
答案 0 :(得分:2)
这样做:
SELECT
t.*
FROM
t
INNER JOIN
(SELECT
Column1
FROM
t
WHERE
Column2 IN (200,201)
GROUP BY
Column1
HAVING
COUNT(DISTINCT Column2)>1) AS c
ON t.Column1=c.Column1
- 但请注意,这将输出包含所有Column2
值的行(例如,不仅200
和201
),如果它不是意图,请过滤它们:
SELECT
t.*
FROM
t
INNER JOIN
(SELECT
Column1
FROM
t
WHERE
Column2 IN (200,201)
GROUP BY
Column1
HAVING
COUNT(DISTINCT Column2)>1) AS c
ON t.Column1=c.Column1
WHERE
Column2 IN (200,201)
小提琴可用here。