显示来自两个外键的列数据

jtjikinw  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(195)

我很困惑,想知道如何显示一个表,它有两列(城市名称)基于两个不同的外键。在本例中,我想显示一个制造商城市和一个仓库城市,而这两个城市都需要访问cityid。

到目前为止,我得出的结论是:

SELECT s.StkName, c.CityName AS "Manufacturer City", c.CityName AS 
"Warehouse City", s.SellingPrice FROM
STOCKITEM7364 s
LEFT OUTER JOIN MANUFACTURER7364 m ON m.ManID = s.ManID
LEFT OUTER JOIN CITY7364 c ON c.CityID = m.CityID
LEFT OUTER JOIN WAREHOUSE7364 w ON w.WHID = s.WHID AND w.CityID = c.CityID
WHERE s.StkName LIKE '%n' OR s.StkName LIKE '%e' OR s.StkName LIKE '%o' OR 
s.StkName LIKE '%p' OR s.StkName LIKE '%s';

我真的很感谢任何关于sql的帮助或解释

emeijp43

emeijp431#

您需要两次加入city name表,一次用于制造商,一次用于仓库。试试这个:

SELECT s.StkName, cm.CityName AS "Manufacturer City", cw.CityName AS 
"Warehouse City", s.SellingPrice FROM
STOCKITEM7364 s
LEFT JOIN MANUFACTURER7364 m ON m.ManID = s.ManID
LEFT JOIN CITY7364 cm ON c.CityID = m.CityID
LEFT JOIN WAREHOUSE7364 w ON w.WHID = s.WHID
LEFT JOIN CITY7364 cw ON c.CityID = w.CityID
WHERE s.StkName LIKE '%n' OR s.StkName LIKE '%e' OR s.StkName LIKE '%o' OR 
s.StkName LIKE '%p' OR s.StkName LIKE '%s';

请注意 OUTER 中不需要 LEFT JOIN .

相关问题