如何修改SQL语句,实现无对应Fixture记录时返回计数0?
修改SQL实现全网站赛程条目统计(含无数据时显示0)
现有表结构及数据
网站表(Websites)
| website_Id | website_name |
|---|---|
| 1 | website_a |
| 2 | website_b |
| 3 | website_c |
| 4 | website_d |
| 5 | website_e |
赛程表(Fixtures)
| fixture_Id | website_id | fixture_details |
|---|---|---|
| 1 | 1 | a vs b |
| 2 | 1 | c vs d |
| 3 | 2 | e vs f |
| 4 | 2 | g vs h |
| 5 | 4 | i vs j |
期望输出
统计每个网站对应的赛程条目数,无对应条目时TotalRows显示0:
| website_Id | website_name | TotalRows |
|---|---|---|
| 1 | website_a | 2 |
| 2 | website_b | 2 |
| 3 | website_c | 0 |
| 4 | website_d | 1 |
| 5 | website_e | 0 |
原SQL问题
当前使用的SQL无法返回无对应赛程的网站条目,原语句如下:
Select fx.website_id, ws.website_name, Count (*) as TotalRows FROM fixtures fx LEFT JOIN websites ws on ws.website_id = fx.website_id WHERE date_of_entry = '16-01-2023' GROUP BY fx.website_id, ws.website_name
修改后的SQL及说明
正确SQL语句
SELECT ws.website_id, ws.website_name, COUNT(fx.fixture_Id) AS TotalRows FROM websites ws LEFT JOIN fixtures fx ON ws.website_id = fx.website_id AND fx.date_of_entry = '16-01-2023' GROUP BY ws.website_id, ws.website_name ORDER BY ws.website_id
核心修改原因:
- 主表切换:以
websites作为主表进行左连接,确保所有网站记录都被保留,哪怕没有匹配的赛程数据 - 条件位置调整:将日期筛选条件移到
JOIN关联条件中,避免WHERE过滤掉左连接产生的空行(无赛程数据的网站) - 统计字段优化:使用
COUNT(fx.fixture_Id)代替COUNT(*),因为赛程表的主键在无匹配时会为NULL,COUNT会忽略NULL值,从而返回0;而COUNT(*)会把主表的空行统计为1,不符合需求
内容的提问来源于stack exchange,提问作者JMon
相关产品推荐
相关产品推荐

