爱
问题的权利。
SELECT *,t.id AS threadid FROM threads t
LEFT JOIN players p on p.id = t.last_poster
WHERE t.boardid = $boardid
我在线程中有两个字段posterid
和lastposterid
。哪个是线程启动器/最后一张海报的ID。我想做的是从玩家表中获取他们的名字。
但是怎么样?
答案 0 :(得分:3)
你只需要两次加入你的玩家表,就像这样。
SELECT
threads.*,
starterPlayer.*,
lastPosterPlayer.*
FROM
threads
LEFT OUTER JOIN
players starterPlayer
ON
starterPlayer.id = threads.posterid
LEFT OUTER JOIN
players lastPosterPlayer
ON
lastPosterPlayer.id = threads.lastposterid
答案 1 :(得分:1)
您可以两次加入同一个表,并为表提供不同的别名。
这假设总会有第一张和最后一张海报,如果是这种情况,那么你需要INNER JOIN
而不是LEFT JOIN
,你需要更改select语句才能得到相关领域。
SELECT t.id AS threadid, playerFirst.name AS FirstPoster, playerLast.name as LastPoster
FROM threads t
INNER JOIN
players playerFirst ON playerFirst.id = t.posterid
INNER JOIN
players playerLast ON playerLast.id = t.lastposterid
答案 2 :(得分:0)
怎么样......
SELECT *,
(SELECT name
FROM players
WHERE players.id = threads.posterid) AS poster,
(SELECT name
FROM players
WHERE players.id = threads.lastposterid) AS last_poster
FROM threads;