多个sql表选择

时间:2013-06-14 13:23:23

标签: sql select join multiple-tables multiple-select

有客户和节日的桌子。每个节日每年都会举行(如新年)。但并非所有客户都被邀请参加任何节日。

我需要得到女性客户,此时被邀请参加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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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'

答案 2 :(得分: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
        );

<强> Example on SQL Fiddle

答案 3 :(得分:0)

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

其次,您需要丢弃受邀参加festival2的客户

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