gpt4 book ai didi

mysql选择每个月的记录数

转载 作者:可可西里 更新时间:2023-11-01 06:46:09 24 4
gpt4 key购买 nike

我需要在 mysql 中创建一个查询,该查询将返回 12 行(每个月一行)以选择月份名称以及给定月份的记录数。我有两个表,months_tbl 和 events_tbl。 events_tbl 中的每条记录都有一个 datetime 列和一个 company_id 列。

我目前正在做类似的事情(注意我还没有 WHERE company_id 子句):

SELECT months_tbl.month, COUNT( events_tbl.event_id ) cnt
FROM months_tbl
LEFT JOIN events_tbl ON months_tbl.month_id = MONTH( events_tbl.appt_date_time )
GROUP BY months_tbl.month
ORDER BY months_tbl.month_id ASC;

这会返回我所期望的结果(选择了 12 行,包含当月的事件计数,如果没有则为零):

**month**    **cnt**
January 0
February 0
March 0
April 0
May 0
June 0
July 0
August 88
September 99
October 120
November 0
December 9

然而,无论公司如何,它都会返回所有记录。我需要确保查询被 so 过滤,我添加了 where 子句:

SELECT months_tbl.month, COUNT( events_tbl.appt_id ) cnt
FROM months_tbl
LEFT JOIN events_tbl ON months_tbl.month_id = MONTH( events_tbl.appt_date_time )
WHERE events_tbl.company_id = 1
GROUP BY months_tbl.month
ORDER BY months_tbl.month_id ASC;

当我添加 where 子句时,我的结果变为:

**month**    **cnt**
August 88
September 99
October 120
December 9

为什么我在添加 where 子句时会丢失所有其他月份的记录,即使我使用的是左连接?

最佳答案

您正在使用 LEFT JOIN,但在您的 where 语句中您将其设为“正常”JOIN

试试这样写:

SELECT months_tbl.month, COUNT( events_tbl.appt_id ) cnt
FROM months_tbl
LEFT JOIN events_tbl ON (months_tbl.month_id = MONTH(events_tbl.appt_date_time)
AND events_tbl.company_id = 1
)
GROUP BY months_tbl.month
ORDER BY months_tbl.month_id ASC;

请注意 AND events_tbl.company_id = 1LEFT JOIN

关于mysql选择每个月的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11841549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com