【问题标题】:Simple MySQL join doesn't work简单的 MySQL 连接不起作用
【发布时间】:2012-01-11 04:55:41
【问题描述】:

我正在尝试选择 cmets 并汇总有关其相应投票的统计信息。并非每条评论都有投票,有投票的评论可以有超过 1 票。这是我的查询:

select
    `article-comments`.id,
    `article-comments`.user as user_id,
    concat(users.first_name, ' ', users.last_name) as name,
    users.job_title,
    users.company_name,
    avatar,
    `article-comments`.content,
    datediff(now(), `article-comments`.date_added) as diff,
    `article-comments`.date_added as date,
    count(`comment-votes`.id) as votes_count,
    sum(`comment-votes`.score) as votes_score
from
    `article-comments` left outer join `comment-votes` on `article-comments`.id = `comment-votes`.comment,
    users
where
    `article-comments`.status = 1
 && `article-comments`.article = $resource_id
 && `article-comments`.user = users.id
 && `comment-votes`.status = 1
order by
    `article-comments`.id asc

它在没有连接的情况下完美运行,但只返回 1 行。

有什么想法吗?

【问题讨论】:

  • 当你说它完美运行时,它是否在没有加入的情况下给你想要的结果?
  • 如果您简化查询以隔离问题会更容易提供帮助 - 删除 SELECT 中不必要的列,并对 WHERE 子句中的值进行硬编码 - 什么是 $table 和 $resource_id ?
  • @Adam - 是的,减去 2 个汇总统计 count() 和 sum()
  • @Mike - 我在尝试调试它时做过,但没有任何效果。我从原始帖子中编辑了 $table,$resource_id 是文章 ID。
  • (与问题无关)不要使用&&。使用AND

标签: mysql join outer-join


【解决方案1】:

试试:

select
                `article-comments`.id,
                `article-comments`.user as user_id,
                concat(users.first_name, ' ', users.last_name) as name,
                users.job_title,
                users.company_name,
                avatar,
                `article-comments`.content,
                datediff(now(), `article-comments`.date_added) as diff,
                `article-comments`.date_added as date,
                count(`comment-votes`.id) as votes_count,
                sum(`comment-votes`.score) as votes_score
            from
                `article-comments` left join `comment-votes` on (`article-comments`.id = `comment-votes`.comment),
                users
            where
                `article-comments`.status = 1
             && `article-comments`.$table = $resource_id
             && `article-comments`.user = users.id
            order by
                `article-comments`.id asc

【讨论】:

  • 谢谢,但它仍然返回同一行:[
  • 使用 COUNT 和 SUM 等聚合函数将得到您所看到的结果,始终是单行。想想经典的“SELECT COUNT(*) FROM atable”来获取该表中的行数。您应该使用 GROUP BY 和这些函数来获取您需要的数据。 MySQL 的默认行为允许某人引用未包含在 GROUP BY 语句中的字段,这会导致一些不确定的结果。如果您想了解更多关于该主题的信息,请阅读此内容dev.mysql.com/doc/refman/5.0/en/…
猜你喜欢
  • 2010-10-10
  • 2013-09-29
  • 2018-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 2012-09-13
相关资源
最近更新 更多