需要简单加入的帮助

时间:2010-07-13 09:40:32

标签: sql join left-join inner-join

问题的权利。

SELECT *,t.id AS threadid FROM threads t 
LEFT JOIN players p on p.id = t.last_poster 
WHERE t.boardid = $boardid

我在线程中有两个字段posteridlastposterid。哪个是线程启动器/最后一张海报的ID。我想做的是从玩家表中获取他们的名字。

但是怎么样?

3 个答案:

答案 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;