这是我的疑问:
SELECT a.id, a.hostname, a.asset_tag, d.model, b.location,
c.type, a.earmarked, a.earmarked_office, a.earmarked_user,
a.earmarked_date, a.earmarked_by
FROM laptops a
JOIN locations b ON a.location = b.id
JOIN types c ON a.type = c.id
JOIN models d ON a.model = d.id
WHERE b.stock = 1
现在,a.earmarked_office
字段实际上是locations
表中ID的引用,我们已经用它来填充b.location
。如何在同一语句中检索earmarked_office
的实际位置名称?
答案 0 :(得分:3)
两次加入桌子:
SELECT lt.id, lt.hostname, lt.asset_tag, d.model, l.location,
c.type, lt.earmarked, lt.earmarked_office, lt.earmarked_user,
lt.earmarked_date, lt.earmarked_by,
lteo.??
FROM laptops lt JOIN
locations l
ON lt.location = l.id JOIN
types t
ON lt.type = t.id JOIN
models m
ON lt.model = m.id JOIN
locations leo
ON lt.earmarked_office = leo.id
WHERE l.stock = 1;
注意:
as
重命名列,这样他们就不会与来自l
的列发生冲突。LEFT JOIN
。答案 1 :(得分:0)
您可以多次加入同一张桌子:
SELECT a.id, a.hostname, a.asset_tag, d.model, b.location,
c.type, a.earmarked, a.earmarked_office, a.earmarked_user,
a.earmarked_date, a.earmarked_by
FROM laptops a
JOIN locations b ON a.location = b.id
JOIN types c ON a.type = c.id
JOIN models d ON a.model = d.id
JOIN locations e ON a.earmarked_office = e.id
WHERE b.stock = 1