如何连接表中列具有我想要的所有值的表?

时间:2012-12-09 19:57:40

标签: sql

我有一个表A,其中B_ID列引用表B中的B_ID 表B将B_ID作为主键,C_ID引用表C中的C_ID

我想从A_ID上的A连接B中选择B.C_ID = 5 AND B.C_ID = 4

例如,当我这样做时:

select from A join B on B.A_ID = A.A_ID

如果结果是:

A_ID  |  B_ID  |  C_ID
 1    |   1    |   4
 1    |   2    |   5

然后我希望查询返回两行 但如果结果是:

A_ID  |  B_ID  |  C_ID
 1    |   1    |   4

我希望查询返回0行。

3 个答案:

答案 0 :(得分:1)

SELECT * FROM A INNER JOIN B ON A.B_ID = B.B_ID
WHERE EXISTS(SELECT * FROM B WHERE C_ID = 4)
AND EXISTS(SELECT * FROM B WHERE C_ID = 5)

会工作 - 可能有更好的方法,让我想想......

(当然上面假设你表中只有1/2行)

SELECT * FROM A
INNER JOIN B ON A.B_ID = B.B_ID
WHERE (SELECT COUNT(*) FROM B WHERE C_ID IN (4,5)) > 1

玩弄它!

答案 1 :(得分:0)

试试这个

SELECT
    whatever
FROM
    A
    INNER JOIN B
        ON A.A_ID = B.A_ID
WHERE
    B.C_ID IN (4, 5)

SELECT
    whatever
FROM
    A
    INNER JOIN B
        ON A.A_ID = B.A_ID
WHERE
    B.C_ID = 4 OR B.C_ID = 5

<强>更新

如果您只想配对

SELECT
    whatever
FROM
    A
    INNER JOIN B
        ON A.A_ID = B.A_ID
WHERE
    A.A_ID IN (SELECT A_ID
               FROM B
               WHERE C_ID IN (4, 5)
               GROUP BY A_ID
               HAVING COUNT(*) = 2) AND
    B.C_ID IN (4, 5)

A_ID选择子组并对记录进行计数。 HAVING子句的工作方式与WHERE子句类似,但在分组后执行。因此内部选择仅返回A_ID对应于{4}的C_ID对。SELECT B.* FROM A INNER JOIN B ON A.A_ID = B.A_ID WHERE B.C_ID IN (4, 5) AND A.A_ID IN (SELECT A_ID FROM B GROUP BY A_ID HAVING MIN(C_ID)=4 AND MAX(C_ID)=5 AND COUNT(*)=2) 。整个查询总是返回偶数个记录,如

A_ID  |  B_ID  |  C_ID
 1    |   1    |   4
 1    |   2    |   5
 2    |   3    |   4
 2    |   4    |   5

修改

如果您只想要A_ID,其中不仅存在C_ID 4和5但不存在其他C_ID,则将查询更改为

COUNT(*)=2

如果两个数字(本例中为4和5)始终是连续的,则可以删除A_ID部分。

(注意:根据您的一条评论,加入位于SELECT * FROM A a INNER JOIN B ON a.A_ID = B.A_ID WHERE (SELECT COUNT(*) FROM B b WHERE b.A_ID = a.A_ID and C_ID IN (4, 5)) = (SELECT COUNT(*) FROM A aa INNER JOIN B b ON aa.A_ID = b.A_ID WHERE b.A_ID = a.A_ID) 列。我在所有示例中都进行了更改。)

罗宾更新

谢谢,在你的帮助下我想出了这个:

{{1}}

答案 2 :(得分:0)

 select B.* from
    A join B on B.B_ID = A.B_ID, 
    (
    select 1 as test from 
    (
    select distinct c_Id from 
    A join B on B.B_ID = A.B_ID
    where c_Id in (4,5)
    ) tmp
    having COUNT(*) = 2
    ) tmp2
    where tmp2.test = 1