【问题标题】:Easier way of using Joins使用联接的更简单方法
【发布时间】:2011-03-16 15:29:37
【问题描述】:

我有以下表格:

作者:

id 用户名 电子邮件 密码 salt email_salt email_verified ip_address

作者线程:

thread_id, author_id

线程:

id、标题、内容、创建

标签:

身份证,姓名

线程标签:

tad_id,thread_id

我想选择最新的 30 个主题、它们的作者和它们的所有标签。这是我使用的 SQL 语句:

       SELECT thread.title, thread.id as thread_id,
       thread.content, author.username, author.id as author_id,
       GROUP_CONCAT(DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',') AS tags
       FROM thread 
       JOIN thread_tags ON thread.id = thread_tags.thread_id
       JOIN tag ON thread_tags.tag_id = tag.id

       JOIN author_threads ON thread.id = author_threads.thread_id
       JOIN author ON author_threads.author_id = author.id

       GROUP BY thread.id DESC
       LIMIT 0, 30

有没有更简单的方法?

【问题讨论】:

  • 这是 MySQL 吗?您应该包括数据库类型标签。

标签: mysql join


【解决方案1】:

我假设 GROUP BY 应该是 ORDER BY?

除此之外,我相信你这样做是对的。

由于您需要来自所有表的值,因此您需要将它们全部连接起来,这就是您所做的。

【讨论】:

  • 不,GROUP BY 子句是正确的;他使用名为GROUP_CONCAT 的MySQL 字符串聚合将标签连接到逗号分隔的列表中,尽管SQL 不合法,因为他在SELECT 子句中选择了非分组和非聚合列。
  • DESC 因为我希望最新的成为第一个
【解决方案2】:

您唯一的其他选择是使用多表选择,例如

   SELECT thread.title, thread.id as thread_id,
   thread.content, author.username, author.id as author_id,
   GROUP_CONCAT(DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',') AS tags
   FROM thread, thread_tags, tag, author_threads, author
   WHERE thread.id = thread_tags.thread_id
       AND thread_tags.tag_id = tag.id
       AND thread.id = author_threads.thread_id
       AND author_threads.author_id = author.id
   GROUP BY thread.id DESC
   LIMIT 0, 30

对此的支持可能取决于数据库。

【讨论】:

  • 啊! 为山峰尖叫
  • 嗯,可能反应过度,但我个人建议不要使用这种(诚然语法正确)风格。 OP 使用的样式存在,因为它更易于维护:)
  • 很公平 - 我已经习惯了这种风格,因为它似乎是我目前工作场所使用的首选语法。
  • 对此的支持不依赖于 RDBMS,但请注意,这是一种已弃用的样式,不应用于新开发。 join 关键字是在 SQL/92 中引入的,是描述查询中连接的首选方式。
  • 另请注意,在所有 RDBMS 的 except MySQL,并且不是 ANSI 兼容的 SQL。
猜你喜欢
  • 1970-01-01
  • 2010-12-17
  • 2016-11-14
  • 2019-10-16
  • 2015-12-03
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 2014-03-12
相关资源
最近更新 更多