简体   繁体   English

如果存在 2 条记录,则 SQL 从表中选择

[英]SQL select from a table if 2 records exist

Say I have a simple table Foo with columns Customer_ID and App_ID假设我有一个包含Customer_IDApp_ID列的简单表Foo

I'm trying to select all customers from CUSTOMER table who have both App 1 and App 2 in Foo table.我正在尝试从CUSTOMER表中选择在Foo表中同时具有App 1App 2所有客户。

I can do我可以

SELECT C FROM CUSTOMER C 
INNER JOIN FOO F ON 
F.CUSTOMER_ID = C.ID
INNER JOIN APP A ON 
A.ID = F.APP_ID
WHERE A.NAME = 'App 1`

But that only gives me results when a customer has 1 app, i want results only if both apps are in Foo .但这仅在客户拥有 1 个应用程序时才给我结果,只有当两个应用程序都在Foo ,我才想要结果。

I would phrase this using exists logic:我会使用存在逻辑来表达这一点:

SELECT C.*
FROM CUSTOMER C 
INNER JOIN FOO F
    ON F.CUSTOMER_ID = C.ID
WHERE
    EXISTS (SELECT 1 FROM APP A WHERE A.ID = F.APP_ID AND A.NAME = 'App 1') AND
    EXISTS (SELECT 1 FROM APP A WHERE A.ID = F.APP_ID AND A.NAME = 'App 2');

If you wanted to this via joining, then you would need two joins to the APP table, eg如果您想通过加入来实现这一点,那么您需要对APP表进行两次连接,例如

SELECT DISTINCT C.*
FROM CUSTOMER C 
INNER JOIN FOO F
    ON F.CUSTOMER_ID = C.ID
INNER JOIN APP A1
    ON A1.ID = F.APP_ID
INNER JOIN APP A2
    ON A2.ID = F.APP_ID
WHERE
    A1.NAME = 'App 1' AND
    A2.NAME = 'App 2';

Note that I am using a distinct select above, because joining to APP twice may generate duplicate records.请注意,我在上面使用了不同的选择,因为两次加入APP可能会生成重复的记录。 Removing possible duplicates represents an extra step in the join approach which won't happen when using exists.删除可能的重复项代表了连接方法中的一个额外步骤,这在使用exists 时不会发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM