1

有客户和节日的桌子。每个节日每年都会发生(如新年)。但并不是每个客户都被邀请参加任何节日。

我需要找到女性客户,她们现在在festival1 上被邀请,但在festival2 上没有被邀请。

Table "clients"
+-----+--------------+-----------+---------+-----+
| id  | name         | email     | adress  | sex |
+-----+--------------+-----------+---------+-----+
| 1   | Ivan         | iva@ya.su | NY city | m   |
| 2   | Michael      | lad@ya.su | LA      | m   |
| 3   | Anna         | al@ya.su  | LA      | w   |
| ...
+-----+--------------+-----------+---------+-----+

Table festivals
+-----+------------+-------+
| id  | name       | date  |
+-----+------------+-------+
| 1   | festival1  | 8-03  |
| 2   | festival2  | 23-02 |
| 3   | festival3  | 1-01  |
| ...
+-----+------------+-------+

Talbe "invitations"
+--------+----------+------+
| client | festival | year |
+--------+----------+------+
| 1      | 2        | 2013 |
| 3      | 1        | 2009 |
| ...
+--------+----------+

我开始做类似这个查询的事情,但需要更正:

SELECT name
    FROM clients, festivals, invitations
    WHERE clients.sex = w
        AND festivals.name = festival1
        AND clients.id = invitations.client
        AND invitations.year = 2013
4

4 回答 4

1

您可以使用NOT EXISTS从查询中消除结果:

SELECT  *
FROM    Clients
        INNER JOIN Invitations
            ON Invitations.Client = Clients.ID
        INNER JOIN Festivals
            ON Festivals.ID = Invitations.Festival
WHERE   Festivals.Name = 'Festival1'
AND     Clients.Sex = 'W'
AND     Invitations.Year = 2013
AND     NOT EXISTS
        (   SELECT  1
            FROM    Invitations i2
                    INNER JOIN Festivals f2
                        ON f2.ID = i2.Festival
            WHERE   i2.Client = Clients.ID
            AND     f2.Name = 'Festival2'
            AND     i2.Year = Invitations.Year
        );

SQL Fiddle 示例

于 2013-06-14T13:59:18.667 回答
1

我会做这样的事情:

SELECT c.Name
   FROM clients c
    INNER JOIN invitations i 
        ON i.client = c.id 
        AND i.year = 2013
    INNER JOIN festivals f 
        ON i.festival = f.id
        AND f.name = 'festival1'
WHERE 
    c.sex = 'w'
于 2013-06-14T13:35:16.703 回答
1
SELECT c.name
FROM clients c
INNER JOIN invitations i ON c.id = i.client
INNER JOIN festivals f ON f.id = i.festival 
WHERE c.sex = 'w'
AND i.year = 2013
group by c.name
having sum(case when f.name='festival1' then 1 else 0 end) > 0
and sum(case when f.name='festival2' then 1 else 0 end) = 0
于 2013-06-14T13:27:43.760 回答
0

首先,您需要通过以下方式将客户加入节日:客户/邀请,然后是邀请/节日

其次,您需要丢弃受邀参加节日的客户2

SELECT name
    FROM clients, festivals, invitations
    WHERE clients.sex = w
        AND festivals.name = festival1
        AND festivals.name != festival2
        AND clients.id = invitations.client
        AND festivals.id = invitations.festival
        AND invitations.year = 2013
于 2013-06-14T13:36:29.727 回答