在LEFT JOIN查询中包含第三个表

时间:2011-08-05 19:26:13

标签: mysql sql union left-join

我有五个mysql表。
商店

+----+--------------+--------------+
| id | name         | address      |
+----+--------------+--------------+
|  1 | Shop1        | Street1      |
|  2 | Shop2        | Street2      |
|  3 | Shop3        | Street3      |
|  4 | Shop4        | Street4      |
+----+--------------+--------------+

水果

+----+--------------+--------------+
| id | fruit        | price        |
+----+--------------+--------------+
|  1 | Bannana      | 2.5          |
|  2 | Apple        | 2.1          |
|  3 | Orange       | 1.8          |
|  4 | Plum         | 2.2          |
+----+--------------+--------------+

可用性

+----+--------------+--------------+
| id | shop_id      | fruit_id     | 
+----+--------------+--------------+
|  1 | 1            | 2            |
|  2 | 2            | 2            |
|  3 | 1            | 3            |
|  4 | 2            | 1            |
+----+--------------+--------------+

shop_activity

+----+--------------+--------------+--------------+
| id | shop_id      | user_id      | status       |
+----+--------------+--------------+--------------+
|  1 | 2            | 1            | 1            |
|  2 | 3            | 2            | 1            |
|  3 | 1            | 2            | 2            |
|  4 | 2            | 2            | 1            |
+----+--------------+--------------+--------------+

用户

+----+--------------+
| id | name         | 
+----+--------------+
|  1 | Peter        |
|  2 | John         |
+----+--------------+

我有查询

SELECT
    availability.shop_id,
    shops.name

FROM availability

LEFT JOIN shops
ON availability.shop_id=shops.id 

WHERE
fruit_id = 2

结果我获得了ID为2(苹果)的水果的商店名单 我该怎么办才能在查询中包含 shop_activity 表,以便在正确的商店旁边usersid = 1时获取用户的状态。这样的东西......

Shop1, NULL
Shop2, status: 1

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

SELECT
    availability.shop_id,
    shops.name,
     shop_activity.status
FROM availability
LEFT JOIN shops
ON availability.shop_id=shops.id 
LEFT JOIN shop_activity
ON shop_activity.shop_id = availability.shop_id
   and shop_activity.user_id = 1
WHERE
fruit_id = 2

答案 1 :(得分:0)

SELECT
    availability.shop_id,
    shops.name

FROM shops 
LEFT JOIN availability ON availability.shop_id=shops.id 
LEFT JOIN shop_activity ON shop_activity .shop_id=shops.id
WHERE
fruit_id = 2
and users.id=1

尝试将商店作为左连接中的第一个表

答案 2 :(得分:0)

尝试以下方法:

SELECT shops.name, shop_activity.status
FROM shops
    INNER JOIN availability ON availability.shop_id = shops.id
        AND availability.fruit_id = 2
    LEFT JOIN shop_activity ON shops.shop_id = shop_activity.shop_id
        AND shop_activity.user_id = 1

这应该为每个拥有苹果的商店提供一行,但是对于用户没有活动的商店,状态将显示为空,否则显示该用户的状态。