简体   繁体   English

具有相同表的多个联接的SQL

[英]SQL with multiple joins with same tables

I'm building a forum, and I have a problem with a SQL select with many joins. 我正在建立一个论坛,而对于具有许多联接的SQL select却存在问题。 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. posts.lastreply =最后回复用户的ID。

You have to specify an alias for each table using the AS keyword: 您必须使用AS关键字为每个表指定一个别名:

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 . 注意,我如何用不同的名称u1u2调用users表的每个实例。 Also notice how I have specified a column alias to distinguish between the two columns of the same name (eg creatorPhoto and replierPhoto ). 还请注意,我如何指定列别名以区分相同名称的两个列(例如creatorPhotoreplierPhoto )。 This way you can use the name as an index into a PHP associative array a la $post['creatorPhoto'] . 这样,您就可以使用该名称作为索引到一个PHP关联数组一拉 $post['creatorPhoto']

Yes, I've silently changed your inline variable to a parameter. 是的,我已将您的内联变量默认更改为参数。 Take it as a hint. 以此作为提示。 :-D :-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. 除了from子句中缺少别名之外, whereorder by子句还可能存在问题。 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 . 假设所有posts均来自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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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