Mysql LEFT JOIN with count 返回未知列

Posted

技术标签:

【中文标题】Mysql LEFT JOIN with count 返回未知列【英文标题】:Mysql LEFT JOIN with count returns Unknown column 【发布时间】:2019-04-23 12:21:35 【问题描述】:

亲爱的,我有以下查询来计算每个用户的垃圾邮件数量和总订单数

我做了左连接,因为并非所有订单都有垃圾邮件

select users.firstName,users.lastName,users.Id,users.phoneNumber,count(CASE 
                            WHEN comments.`commentType` = "spam" THEN 1 ELSE NULL END) as countSpam,
                            count(`orders`.`id`) as totalOrder
                            from `orders`,users,providers
                            LEFT JOIN comments ON `orders`.`id`= `comments`.`commentableId`
                            where
                            `orders`.`providerId` = `providers`.id
                            and
                            users.id = `providers`.userId
                            and
                            `orders`.`createdAt` >= (CURDATE() - INTERVAL 7 DAY)
                            GROUP BY users.id
                            ORDER BY countSpam DESC;

我从 mysql 收到以下错误

“on 子句”中的未知列“orders.id”

这里有什么问题?我根据旧查询正确地完成了 LEFT JOIN

【问题讨论】:

看起来orders 没有id 列。推荐使用JOIN 对抗usersproviders 它是存在的,亲爱的,因为它是主键 :D 我之前仔细检查过 请不要使用旧的基于逗号的隐式连接,而是使用现代的Explicit Join based syntax。切换到基于ON 子句的代码;您应该能够自动看到错误:-) 此外,在这种多表查询中,通常最好使用别名。 【参考方案1】:

我解决了这个问题,我认为这是语法问题,下面是一个像魅力一样工作的新查询

select users.firstName,users.lastName,users.phoneNumber,count(CASE
                            WHEN comments.`commentType` = "spam" THEN 1 ELSE NULL END) as spamCounter,
                            ROUND(count(CASE
                  WHEN comments.`commentType` = "spam" THEN 1 ELSE NULL END)/count(orders.id),2) AS ratio_spam,
                            count(orders.id) as totalOrder
                            from users,providers,orders
                            LEFT JOIN comments ON `orders`.`id`= `comments`.`commentableId`
                            where
                            orders.`providerId` = providers.id
                            and
                            users.id = providers.userId
                            and
                            `orders`.`createdAt` >= (CURDATE() - INTERVAL 7 DAY)
                            GROUP BY users.id
                            ORDER BY spamCounter DESC
                            LIMIT 20;

【讨论】:

以上是关于Mysql LEFT JOIN with count 返回未知列的主要内容,如果未能解决你的问题,请参考以下文章

MySQL left join with 'b's limit

Mysql left join with nested select慢,如何优化

mysql left join to table with multiple rows on min id 以确保返回单行

MySQL LEFT JOIN with SUM before a date and SUM before and at that date

Mysql JOIN with IN 和 RIGHT 表的多个结果

ORDER BY date SQL with LEFT JOIN 用于消息传递