我有五個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表以獲得用戶的狀態,如果users
。 id
= 1在適當的商店旁邊。事情是這樣的......
Shop1, NULL Shop2, status: 1
我已經試過類似的東西,但它不起作用。因此,我只得到那些有蘋果並且用戶身份存在的商店。我想要所有有蘋果的商店。 – Goldie
不知何故,我仍然得到相同的結果。 – Goldie
@Goldie:不確定,但將'user_id'條件移動到JOIN子句有什麼區別? – FrustratedWithFormsDesigner