简体   繁体   English

SQL NOT EXIST 子查询

[英]SQL NOT EXIST subquery

I have a situation when I have a number of unique site/primary records with child records, and subsequent grandchild records.我的情况是,我有许多带有子记录和后续孙记录的唯一站点/主记录。 I am looking to modify my SQL query so it will populate the unique primary records based on whether or not grandchild records exist, but then further filter down those primary records based on the child record columns.我希望修改我的 SQL 查询,以便它根据孙子记录是否存在来填充唯一的主记录,然后根据子记录列进一步过滤这些主记录。

Eg例如

SELECT PrimaryTable.SiteKey
FROM PrimaryTable
WHERE NOT EXISTS (
    SELECT*
    FROM PrimaryTable, ChildTable, GrandChildTable
    WHERE PrimaryTable.SiteKey = ChildTable.SiteKey
    and Childtable.Key = GrandChildTable.ParentKey)

This works, whereby the list of sites/primary records that have child records, which do not have grandchild records populate.这是有效的,其中具有子记录的站点/主记录列表填充,而没有孙记录。

If I want to further filter on the Primary table, to the end of the query I could add AND PrimaryTable.Column1 = 'MyDesiredValue' and it works fine.如果我想进一步过滤主表,在查询的末尾我可以添加AND PrimaryTable.Column1 = 'MyDesiredValue'并且它工作正常。 However, I want to filter it by ChildTable.Column != 'MyDesiredValue' .但是,我想通过ChildTable.Column != 'MyDesiredValue'过滤它。

When I do this, I get an error that the parameter is not bound, and the ChildTable is not listed at the beginning of the query.当我这样做时,我得到一个错误,该参数未绑定,并且ChildTable未列在查询的开头。

I need the Primary Keys to populate and I cannot use joins using the interface/software I am working with, unfortunately.我需要填充主键,但不幸的是,我无法使用我正在使用的界面/软件使用连接。 Hoping there is a way to modify the query above to make it work.希望有一种方法可以修改上面的查询以使其工作。

FIrst, convert your query to use an outer (ie LEFT) join, that filters out rows with no grand children.首先,将您的查询转换为使用外部(即 LEFT)连接,过滤掉没有大孩子的行。 Then add your filter to the join:然后将您的过滤器添加到联接中:

SELECT distinct PrimaryTable.SiteKey -- distinct, or it'll repeat every join
FROM PrimaryTable
JOIN ChildTable on PrimaryTable.SiteKey = ChildTable.SiteKey -- inner (required) join
    AND ChildTable.Column != 'MyDesiredValue'
LEFT JOIN GrandChildTable on Childtable.Key = GrandChildTable.ParentKey
    AND GrandChildTable.year = 2020
WHERE GrandChildTable.ParentKey IS NULL -- only rows without grandchildren

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

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