【问题标题】:All NOT IN can be converted to NOT EXISTS?所有 NOT IN 都可以转换为 NOT EXISTS 吗?
【发布时间】:2014-09-03 11:05:03
【问题描述】:

我有一个表 FilesContainsFiles,它是一个连接表:

  • FilesContainsFiles(IDContainerFile, IDContentFile)

我想知道哪些包含的文件只包含在特定的容器文件中。

例如,我有一个包含 file01 和 file02 的 fileA 和一个包含 file01 的 fileB。

我想知道哪些文件只包含在fileA中。所以有了 NOT IN 我有:

select * from FilesContainsFiles 
where IDContentFile NOT IN(
select IDContentFile from FilesContainsFiles 
where IDContentFile IN(select IDContentFile 
from FilesContainsFiles where IDContainerFile NOT IN (64)))

注意:我使用 NOT IN 和 IN 是因为我想指定多个 fileContainer。我只能对一个容器使用相等的比较。

但是,当我尝试使用 NOT EXISTS 并且没有得到结果时。我尝试这样的事情:

select * from FilesContainsFiles 
where NOT EXISTS(select * from FilesContainsFiles where IDContainerFile <> 64)

是否可以使用 NOT EXISTS 代替 NOT IN?

谢谢。

【问题讨论】:

    标签: sql not-exists


    【解决方案1】:

    我认为您的IN 查询可以写成

    select * from FilesContainsFiles 
    where IDContentFile NOT IN(select IDContentFile 
    from FilesContainsFiles where IDContainerFile <> 64)
    

    EXISTS 版本一样

    select * from FilesContainsFiles fcf
    where NOT EXISTS (select * from 
    FilesContainsFiles fcf2
    where IDContainerFile <> 64
    and fcf.IDContentFile = fcf2.IDContentFile)
    

    【讨论】:

    • 非常感谢。 NOT IN 版本比我的版本更简单,并且不存在版本工作正常。谢谢。
    【解决方案2】:

    您也可以尝试这样做以达到相同的目标(仅选择 ID=64 的容器中包含的内容文件):

    SELECT IDContentFile, GROUP_CONCAT(IDContainerFile) AS IDContainers 
    FROM FilesContainsFiles
    GROUP BY IDContentFile
    HAVING IDContainers = "64";
    

    【讨论】:

    • 这是 mysql-only(因为 group_concat 并在 having 中使用了表达式别名)。
    猜你喜欢
    • 2014-12-29
    • 1970-01-01
    • 2013-11-18
    • 2021-10-12
    • 1970-01-01
    • 2016-02-11
    • 2015-10-13
    • 2015-07-06
    • 2014-07-18
    相关资源
    最近更新 更多