无法弄清楚我在哪里出错双重否定查询(mysql)

时间:2017-10-12 09:35:55

标签: mysql database

我尝试找到至少具有所有仪表类型的属性(pids)作为属性id 7。我试图使用双重否定查询,但我一直得到错误,我认为我非常接近正确(我发现双重否定概念上很难)有人可以帮我找到我的错误吗?

SELECT DISTINCT pid FROM PROPERTYMETER X WHERE NOT EXISTS (SELECT * FROM PROPERTYMETER Y WHERE pid = 7) AND NOT EXISTS (SELECT * FROM PROPERTYMETER WHERE pid = X.pid AND metertype = Y.metertype)

PROPERTYMETER table METERTYPE table

我只使用了PROPERTYMETER表,但是通过加入PROPERTYMETER和METERTYPE可能有更好的方法吗?

-Thanks

1 个答案:

答案 0 :(得分:0)

One conceptual way to proceed here is to inner join each pid group of meter values to a table consisting only of the meter values for pid=7. Then aggregate by pid and assert that the number of distinct meter types for each pid group matches the number meter types for pid=7.

SELECT
    p1.pid
FROM PROPERTYMETER p1
INNER JOIN PROPERTYMETER p2
    ON p1.metertype = p2.metertype AND
       p2.pid = 7
GROUP BY
    p1.pid
HAVING
    COUNT(DISTINCT p1.metertype) = (SELECT COUNT(DISTINCT metertype)
                                    FROM PROPERTYMETER WHERE pid = 7)

Output:

Only pid 7 and 9 are returned.

Demo here:

Rextester