Oi
爱
Right to the problem.
问题的权利。
SELECT *,t.id AS threadid FROM threads t
LEFT JOIN players p on p.id = t.last_poster
WHERE t.boardid = $boardid
I have two fields in threads called posterid
and lastposterid
. Which are the IDs of the thread starter / last poster. What I want to do is to get their names from players table.
我在线程中有两个字段叫做posterid和lastposterid。哪个是线程启动器/最后一张海报的ID。我想做的是从玩家表中获取他们的名字。
But how?
但是怎么样?
3 个解决方案
#1
1
You can join to the same table twice and give the table a different alias.
您可以两次加入同一个表,并为表提供不同的别名。
This presumes that there always will be a first and last poster, if this is the case then you want an INNER JOIN
rather than a LEFT JOIN
, you will need to change the select statement to get the relevant fields.
这假设总会有第一张和最后一张海报,如果是这种情况,那么你想要一个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
3
You just need to join to your players table twice, like this.
你只需要两次加入你的玩家表,就像这样。
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
#3
0
How about...
怎么样...
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;
#1
1
You can join to the same table twice and give the table a different alias.
您可以两次加入同一个表,并为表提供不同的别名。
This presumes that there always will be a first and last poster, if this is the case then you want an INNER JOIN
rather than a LEFT JOIN
, you will need to change the select statement to get the relevant fields.
这假设总会有第一张和最后一张海报,如果是这种情况,那么你想要一个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
3
You just need to join to your players table twice, like this.
你只需要两次加入你的玩家表,就像这样。
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
#3
0
How about...
怎么样...
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;