简体   繁体   English

SQL-仅当B不存在时选择A

[英]SQL - Select A only if B doesn't exist

I have this SQL statement (modified, because the real query is huge): 我有此SQL语句(已修改,因为实际查询量很大):

select tblInfo.IDNum, tblAddress.PrimaryAddress
from tblInfo
join tblAddress
on tblInfo.Agent = tblAddress.Agent
where (some stuff)

And I get a table that looks roughly like this: 我得到一个大致如下所示的表:

|| IDNum || PrimaryAddress ||
-----------------------------
|| 01234 || 1              ||
|| 23456 || 1              ||
|| abcde || 0              ||
|| abcde || 1              ||
|| zyxwv || 0              ||

I need a way to return all records that have a PrimaryAddress of 1, as well as all records that have a PrimaryAddress of 0 and don't have an IDNum already returning the PrimaryAddress of 1. ie In the above example, (abcde || 0) should be excluded because (abcde || 1) exists. 我需要一种方法来返回所有具有PrimaryAddress为1的记录,以及所有具有PrimaryAddress为0且没有IDNum已经返回PrimaryAddress为1的IDNum的记录。即在上面的示例中,(abcde || 0)应该被排除,因为(abcde || 1)存在。

Use NOT EXISTS 使用NOT EXISTS

SELECT tblInfo.IDNum, tblAddress.PrimaryAddress
FROM tblInfo
INNER JOIN tblAddress
    ON tblInfo.Agent = tblAddress.Agent
WHERE tblAddress.PrimaryAddress = 1
OR  ( tblAddress.PrimaryAddress = 0 AND NOT EXISTS
    (
       SELECT 1 FROM tblInfo t2 INNER JOIN tblAddress a2 ON t2.Agent = a2.Agent
       WHERE t2.IDNum = tblInfo.IDNum AND a2.PrimaryAddress = 1
    )
)

In this case, a simple GROUP BY should work for what you are trying to do. 在这种情况下,一个简单的GROUP BY应该可以满足您的需求。 Effectively you are saying you want all IDNum values to appear once, with the PrimaryAddress value corresponding to the highest value (1 if it exists, 0 if it doesn't). 实际上,您说的是您希望所有IDNum值出现一次,并且PrimaryAddress值对应于最大值(如果存在,则为1,如果不存在,则为0)。

Assuming you need to preserve your original query because you're doing other work with it, you could use: 假设由于要进行其他工作而需要保留原始查询,则可以使用:

SELECT IDNum, MAX(PrimaryAddress) AS PrimaryAddress
FROM
(
    select tblInfo.IDNum, tblAddress.PrimaryAddress
    from tblInfo
    join tblAddress
    on tblInfo.Agent = tblAddress.Agent
    where (some stuff)
)
GROUP BY IDNum

This should work in MS SQL Server and Oracle, not sure about other DBMSs. 这应该可以在MS SQL Server和Oracle中运行,而对于其他DBMS则不确定。 If the nested query doesn't work in the DBMS you're using, you should be able to populate a temporary table with the results of your first query, then perform the grouping against that table. 如果嵌套查询在您使用的DBMS中不起作用,则应该能够使用第一个查询的结果填充临时表,然后对该表进行分组。

I hope this helps 我希望这有帮助

select * from tblAddress mainTBL
where mainTBL.primaryaddress = (Case when EXISTS(select t1.IDNUM from tblAddress t1 where
           mainTBL.IDNUM = t1.IDNUM AND t1.primaryAddress = 1)  THEN 1 ELSE 0 END)

Check the SQL fiddle 检查SQL小提琴

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

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