双重不存在条款是什么意思?

时间:2013-06-30 15:46:58

标签: mysql sql relational-division

SELECT c.name
FROM   Customer c
WHERE  NOT EXISTS(SELECT w.WID
                  FROM   Woker w
                  WHERE  NOT EXISTS(SELECT la
                                    FROM   look_after la
                                    WHERE  la.CID = c.CID
                                           AND la.WID = w.WID)); 

我不知道代码意味着什么......有人能告诉我代码的作用吗? C是一名顾客,他将照顾一名工人。

2 个答案:

答案 0 :(得分:8)

查询选择所有员工照顾的客户。

not exists是实现relational division的一种方式。

答案 1 :(得分:2)

以Andomar的优秀答案为例说明:

    -- Some test data
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;

CREATE TABLE persons
        ( person_id  INTEGER NOT NULL PRIMARY KEY
        , pname   varchar
        );
INSERT INTO persons( person_id, pname ) VALUES
 (1 , 'Bob' ) ,(2 , 'Alice' ) ,(3 , 'Carol' )
        ;

CREATE TABLE movies
        ( movie_id  INTEGER NOT NULL PRIMARY KEY
        , mname   varchar
        );
INSERT INTO movies( movie_id, mname ) VALUES
 (1, 'The Blues brothers' ), (2, 'Modern Times' ), (3, 'The Sound of Music' )
,(4, 'Amadeus' ), (5, 'Never say Never' )
        ;

        -- people that have seen a particular movie
CREATE TABLE person_movie
        ( person_id  INTEGER NOT NULL
        , movie_id INTEGER NOT NULL
        , PRIMARY KEY ( person_id, movie_id)
        );
INSERT INTO person_movie( person_id, movie_id) VALUES
 (1 ,5 ) ,(1 ,1 )
,(2 ,5 ) ,(2 ,4 ) ,(2 ,1 ) ,(2 ,3 ) ,(2 ,2 )
,(3 ,1 ) ,(3 ,3 )
        ;

        -- Find the people that have seen ALL the movies
        -- This is equivalent to:
        -- Find persons for whom NO movie exists that (s)he has NOT seen
SELECT * FROM persons p
WHERE NOT EXISTS (
        SELECT * FROM movies m
        WHERE NOT EXISTS (
                SELECT * FROM person_movie pm
                WHERE pm.movie_id = m.movie_id
                AND pm.person_id = p.person_id
                )
        );

        -- similar: Find the movies that have been seen by ALL people
SELECT * FROM movies m
WHERE NOT EXISTS (
        SELECT * FROM persons p
        WHERE NOT EXISTS (
                SELECT * FROM person_movie pm
                WHERE pm.movie_id = m.movie_id
                AND pm.person_id = p.person_id
                )
        );                                             

结果:

 person_id | pname 
-----------+-------
         2 | Alice
(1 row)

 movie_id |       mname        
----------+--------------------
        1 | The Blues brothers
(1 row)