Sql 使用联接从三个表检索数据

Sql 使用联接从三个表检索数据,sql,Sql,我有以下表格: Post (id, title, author_id) etc Tags Post_tags Author 下面的sql查询似乎只获取第一个线程以及所有标记 SELECT post. * , author.username, GROUP_CONCAT( DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',' ) AS tags FROM author, post JOIN post_tags ON post.id = pos

我有以下表格:

Post (id, title, author_id) etc
Tags
Post_tags
Author
下面的sql查询似乎只获取第一个线程以及所有标记

SELECT post. * , author.username,
GROUP_CONCAT( DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',' ) AS tags
FROM author, post
JOIN post_tags ON post.id = post_tags.thread_id
JOIN tag ON post_tags.tag_id = tag.id
WHERE author.id = post.author_id

我做错了什么?

您通常使用
GROUP\u CONCAT()
GROUP BY
子句

如果没有
GROUP BY
,则意味着它将所有行分组为一行,从而显示所有标记的组连接

您看到的第一个线程数据是MyQSL不良行为的副产品,它允许您在SELECT中显示不依赖于分组字段的字段(在您的示例中没有)

请尝试在查询末尾添加
按post.id分组

SELECT post. *
     , author.username
     , GROUP_CONCAT( DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',' )
         AS tags

FROM author
  JOIN post
    ON author.id = post.author_id
  JOIN post_tags
    ON post.id = post_tags.thread_id
  JOIN tag
    ON post_tags.tag_id = tag.id

GROUP BY post.id

通常将
GROUP\u CONCAT()
groupby
子句一起使用

如果没有
GROUP BY
,则意味着它将所有行分组为一行,从而显示所有标记的组连接

您看到的第一个线程数据是MyQSL不良行为的副产品,它允许您在SELECT中显示不依赖于分组字段的字段(在您的示例中没有)

请尝试在查询末尾添加
按post.id分组

SELECT post. *
     , author.username
     , GROUP_CONCAT( DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',' )
         AS tags

FROM author
  JOIN post
    ON author.id = post.author_id
  JOIN post_tags
    ON post.id = post_tags.thread_id
  JOIN tag
    ON post_tags.tag_id = tag.id

GROUP BY post.id

您通常使用
GROUP\u CONCAT()
GROUP BY
子句。标题应该是四个表是的,我一创建它就更改了,您正在查看(mem?)缓存的版本您通常使用的
GROUP\u CONCAT()
带有一个
GROUP BY
子句。标题应该是四个表。是的,我一创建它就更改了它,您正在查看(mem?)缓存版本