简体   繁体   English

SQL多重连接SELECT查询

[英]SQL multiple joins SELECT query

I've build the following query 我构建了以下查询

$subforumsquery = "
        SELECT
          forums.*,
          posts.title   AS lastmsgtitle,
          posts.timee   AS lastmsgtime,
          posts.useraid AS lastmsguseraid,
          posts.useradn AS lastmsguseradn,
          users.photo   AS lastmsgphoto
        FROM forums
          LEFT JOIN posts
            ON (posts.forumid = forums.id)
          LEFT JOIN users
            ON (posts.useraid = users.id)
        WHERE forums.relatedto = '$forumid'
            and posts.type = 'post'
        ORDER BY `id` DESC";

I don't know why, but i get the same subforum twice even that there is only 1 sub forum. 我不知道为什么,但即使只有一个子论坛,我也会得到两次相同的子论坛。

BTW, is there any way to select only the last post insted of searching all? 顺便说一句,有没有办法只选择最后一个搜索所有的帖子?

Thanks! 谢谢!

Use group by 使用分组依据

SELECT
  forums.*,
  posts.title   AS lastmsgtitle,
  posts.timee   AS lastmsgtime,
  posts.useraid AS lastmsguseraid,
  posts.useradn AS lastmsguseradn,
  users.photo   AS lastmsgphoto
FROM forums
  LEFT JOIN posts
    ON (posts.forumid = forums.id)
  LEFT JOIN users
    ON (posts.useraid = users.id)
WHERE forums.relatedto = '$forumid'
    and posts.type = 'post'
GROUP BY forums.id
ORDER BY `id` DESC

EDIT : 编辑:

Use MAX with a derieved query 使用带有查询的MAX

SELECT
  forums.*,
  posts.title   AS lastmsgtitle,
  posts.timee   AS lastmsgtime,
  posts.useraid AS lastmsguseraid,
  posts.useradn AS lastmsguseradn,
  users.photo   AS lastmsgphoto
FROM forums
  LEFT JOIN (
        SELECT  
            * 
        FROM posts
        LEFT JOIN (
                SELECT 
                    MAX(id) AS ID 
                FROM posts 
                GROUP BY forumid
            ) AS l ON l.ID = posts.id
     GROUP BY forumid) AS posts
    ON posts.forumid = forums.id
  LEFT JOIN users
    ON (posts.useraid = users.id)
WHERE forums.relatedto = '$forumid'
    and posts.type = 'post'
GROUP BY forums.id
ORDER BY `id` DESC

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

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