Include third table in LEFT JOIN query
I have five mysql tables.
shops+----+--------------+--------------+ | id | name | address | +----+--------------+--------------+ | 1 | Shop1 | Street1 | | 2 | Shop2 | Street2 | | 3 | Shop3 | Street3 | | 4 | Shop4 | Street4 | +----+--------------+--------------+
fruits
+----+--------------+--------------+ | id | fruit | price | +----+--------------+--------------+ | 1 | Bannana | 2.5 | | 2 | Apple | 2.1 | | 3 | Oran开发者_运维百科ge | 1.8 | | 4 | Plum | 2.2 | +----+--------------+--------------+
availability
+----+--------------+--------------+ | 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 | +----+--------------+--------------+--------------+
users
+----+--------------+ | id | name | +----+--------------+ | 1 | Peter | | 2 | John | +----+--------------+
I have query
SELECT
availability.shop_id,
shops.name
FROM availability
LEFT JOIN shops
ON availability.shop_id=shops.id
WHERE
fruit_id = 2
As a result I get name list of shops where fruit with id 2 (apple) is available.
What should I do so that I can include shop_activity table in query to get user's status ifusers
.id
= 1 beside proper shop. Something like this...
Shop1, NULL Shop2, status: 1
You could try something like this:
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
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
try making shops as the first table in left join
Try the following:
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
This should give you a row for every shop with apples, but the status will show as null for shops where the user has no activity, otherwise shows the status of that user.
精彩评论