2011-08-05 56 views
1

我有五個mysql表。
商店在LEFT JOIN查詢中包含第三個表

 
+----+--------------+--------------+ 
| 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 

回答

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 
+0

我已經試過類似的東西,但它不起作用。因此,我只得到那些有蘋果並且用戶身份存在的商店。我想要所有有蘋果的商店。 – Goldie

+0

不知何故,我仍然得到相同的結果。 – Goldie

+0

@Goldie:不確定,但將'user_id'條件移動到JOIN子句有什麼區別? – FrustratedWithFormsDesigner

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 

嘗試使商店作爲第一臺在左加入

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 

這應該會爲每個店鋪提供一排蘋果,但是如果用戶沒有活動,店鋪的狀態將顯示爲空白,否則會顯示該用戶的狀態。