MySQL加入查询问题

时间:2011-03-18 16:23:46

标签: mysql join

我有以下表格。

PHONES
 - id
 - name
 - colour
 - size

STOCK
 - store_id
 - phone_id
 - instock

STORES
 - id
 - name

LINKS
 - store_id
 - phone_id
 - url

我想从PHONES中选择名称,颜色,大小,来自STOCK的instock,来自STORES的名称,以及来自LINKS WHERE stock.phone_id = phones.id = links.phone_id AND stock.store_id = links.store_id AND stores的url。 id = stock.store_id。

我想要put,phone.name,phone.colour,phone.size,stock.instock,stores.name,links.url。

这是我当前的查询。我没有收到与该商店和电话ID相关的特定链接。

SELECT DISTINCT(s.phone_id), st.name, st.logo_url, l.url, s.instock, s.datetime, p.model, p.colour, p.size 
FROM stock AS s, stores AS st 
INNER JOIN links AS l, phones AS p 
WHERE s.phone_id = p.id 
AND s.phone_id = l.phone_id 
AND s.store_id = l.store_id 
AND s.store_id IN ('3','4','5','6','8') 
AND s.phone_id = '5' 
ORDER BY datetime 
DESC LIMIT 5

1 个答案:

答案 0 :(得分:3)

SELECT p.name, p.colour, p.size, st.instock, s.name, l.url
FROM phones p
INNER JOIN links l ON l.phone_id = p.id
INNER JOIN stores s ON s.id = l.store_id
INNER JOIN stock st ON st.store_id = s.id AND st.phone_id = p.id
WHERE s.id IN ('3', '4', '5', '6', '8')
AND p.id = '5'

datetime未在您的表格描述中定义,因此我忽略了将其添加到查询中,但这应该提供您正在查找的内容。