我有一个包含3个字段ID,A,B的表。 我想从某个ID中找到每个A中出现的每个B
例如:
ID | A | B |
----------------------
1 | 10 | 22 |
1 | 10 | 24 |
1 | 11 | 22 |
| | |
2 | 12 | 31 |
2 | 13 | 33 |
| | |
3 | 14 | 34 |
应该返回:
ID | B |
-------------
1 | 22 |
3 | 34 |
因为对于来自ID 1的A的每个不同值,发生B = 22。 同样适用于身份3。
知道我该怎么办吗?
提前谢谢。
答案 0 :(得分:1)
<强> Sql Fiddle Demo 强>
您可以使用此查询来验证您需要的行。
(Key,Field)
但这会提供你想要的结果。
SELECT T1.B, T1.ID, COUNT(DISTINCT A), T2.total_id_a
FROM Table1 T1
JOIN (SELECT ID , COUNT(DISTINCT A) as total_id_a
FROM Table1
GROUP BY ID) T2
ON T1.ID = T2.ID
GROUP BY B, ID;
<强>输出强>
SELECT ID, B
FROM (
SELECT T1.ID, T1.B, COUNT(DISTINCT A), T2.total_id_a
FROM Table1 T1
JOIN (SELECT ID , COUNT(DISTINCT A) as total_id_a
FROM Table1
GROUP BY ID) T2
ON T1.ID = T2.ID
GROUP BY B, ID
HAVING COUNT(DISTINCT A) = T2.total_id_a
) T
答案 1 :(得分:0)
# For case ID=1 and B=22 for example above
SELECT DISTINCT t1.ID, t1.B
FROM yourtable AS t1
INNER JOIN yourtable AS t2
ON t2.B = t1.B
AND t2.A <> t1.A
AND t1.ID = t2.ID
UNION
# For case ID=3 and B=34 for example above
SELECT DISTINCT t1.ID, t1.B
FROM yourtable AS t1
INNER JOIN yourtable AS t2
ON t2.B = t1.B
AND t2.A = t1.A
AND t1.ID = t2.ID
LEFT JOIN yourtable AS t3
ON t3.ID = t1.ID
AND (t3.A <> t1.A OR t3.B <> t1.B)
WHERE t3.ID IS NULL