简体   繁体   中英

SQL with multiple joins with same tables

I'm building a forum, and I have a problem with a SQL select with many joins. I want to show two images of different users in the same row.

The first image of the user is who wrote the topic, and the second image is of the user who last replied.

The query I build:

SELECT 
posts.*, users.photo, users.displayname FROM posts 
JOIN users ON(posts.useraid = users.id)
JOIN users ON(posts.lastreply = user.id)
WHERE forumid='$forumid' and type='post' ORDER BY `timee` DESC
  • posts.lastreply = the ID of the last reply user.

You have to specify an alias for each table using the AS keyword:

SELECT posts.*, 
    u1.photo AS creatorPhoto, u1.displayname AS creatorName, 
    u2.photo AS replierPhoto, u2.displayname AS replierName
FROM posts 
JOIN users AS u1 ON(posts.useraid = u1.id)
JOIN users AS u2 ON(posts.lastreply = u2.id)
WHERE forumid= @forumid and type='post' 
ORDER BY `timee` DESC

Notice how I call each instance of the users table by a different name - u1 and u2 . Also notice how I have specified a column alias to distinguish between the two columns of the same name (eg creatorPhoto and replierPhoto ). This way you can use the name as an index into a PHP associative array a la $post['creatorPhoto'] .

Yes, I've silently changed your inline variable to a parameter. Take it as a hint. :-D

In addition to the lack of aliases in the from clause you may also have a problem with the where and order by clause. You need to use aliases for the columns there.

I don't know where they come from, but something like:

WHERE posts.forumid='$forumid' and posts.type='post'
ORDER BY posts.`timee` DESC

Assuming all come from posts .

you need an alias for this to work

SELECT 
posts.*, u1.photo, u1.displayname, u2.photo, u2.displayname FROM posts 
JOIN users u1 ON posts.useraid = u1.id
JOIN users u2 ON posts.lastreply = u2.id
WHERE forumid='$forumid' and type='post' ORDER BY `timee` DESC
SELECT posts.*, author.photo as author_photo, author.displayname as author+name,
       replier.photo as replier_photo, replier.displayname as replier_name
FROM posts 
  JOIN users author ON(posts.useraid = users.id)
  JOIN users replier ON(posts.lastreply = user.id)
WHERE forumid='$forumid' and type='post' ORDER BY `timee` DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM