找到不包含'y'的所有值'x'

时间:2016-04-20 15:56:17

标签: mysql sql

我必须提供所有不包含site

的有效domain的列表
SELECT companies.name,sites.name,sites.association 
FROM companies JOIN sites ON sites.company = companies.id 
JOIN domains ON domains.site != sites.id WHERE sites.is_deleted = 0 
AND domains.is_primary = 1 AND domains.is_deleted = 0

我加入的条件是sites的主键与domains.site字段中的任何内容都不对应。但是,我知道我没有得到我需要的输出,因为我知道我想要的数量或行数,而且我产生的数量不止于此。

我正在使用的te架构的uml图是here(它有点时髦)。

1 个答案:

答案 0 :(得分:2)

如果您尝试查找没有主域名的网站,这可能会为您提供所需内容。它使用左连接并检查域记录是否为空/缺失

SELECT  companies.name,
        sites.name,
        sites.association
FROM    companies
        JOIN sites ON sites.company = companies.id
        LEFT JOIN domains ON domains.site = sites.id
                             AND domains.is_primary = 1
                             AND domains.is_deleted = 0
WHERE   sites.is_deleted = 0
        AND domains.id IS NULL

您还可以考虑使用NOT EXISTS

SELECT  companies.name,
        sites.name,
        sites.association
FROM    companies
        JOIN sites ON sites.company = companies.id
WHERE   sites.is_deleted = 0
        AND NOT EXISTS (
            SELECT 1
            FROM    domains d
            WHERE   d.site = sites.id
                    AND d.is_primary = 1
                    AND d.is_deleted = 0
        )

这是一个sql小提琴,供您测试SQL FIDDLE