需要簡單加入的幫助

[英]Need help with a simple Join


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;

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/07/13/af3f565d471c67ea18e7bf7edc3ab58.html



 
  © 2014-2022 ITdaan.com 联系我们: