MySQL生成日期序列与表关联的 SQL 查询
1、内部日期序列生成
首先,让我们看一下内部日期序列的生成部分。这部分的作用是创建从 2024 年 4 月 1 日开始的日期序列,直到 2024 年 12 月 31 日。SQL 使用 DATE_ADD 函数和一个嵌套的子查询来生成这个日期序列。
SELECT DATE_ADD('2024-04-01', INTERVAL seq.seq DAY) AS DATE FROM ( SELECT (t3.num*100 + t2.num*10 + t1.num) AS seq FROM (SELECT 0 AS num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t1, (SELECT 0 AS num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t2, (SELECT 0 AS num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t3 ) AS seq WHERE DATE_ADD('2024-04-01', INTERVAL seq.seq DAY) <= '2024-12-31';
2、外部表关联
接下来,我们将日期序列与 yonghu 表进行连接。在这个例子中,连接条件是一个始终为真的条件 1=1,这将导致日期序列中的每个日期与 yonghu 表中的所有行进行连接。
SELECT dates.date, yonghu.姓名, yonghu.国家, yonghu.`id2` FROM ( -- 上面的日期序列生成查询 ) AS dates JOIN yonghu ON 1=1;
3、结果分析
最终的结果将包含从 2024 年 4 月 1 日到 2024 年 12 月 31 日的每一天,以及 yonghu 表中每一行的姓名、国家和 id2 列的数据。这种连接方式会生成一个笛卡尔积,因为日期序列中的每个日期都会与 yonghu 表中的所有行进行匹配。
4、完整代码
SELECT dates.date, yonghu.姓名, yonghu.国家,yonghu.`id2` FROM ( SELECT DATE_ADD('2024-04-01', INTERVAL seq.seq DAY) AS DATE FROM ( SELECT (t3.num*100 + t2.num*10 + t1.num) AS seq FROM (SELECT 0 AS num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t1, (SELECT 0 AS num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t2, (SELECT 0 AS num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t3 ) AS seq WHERE DATE_ADD('2024-04-01', INTERVAL seq.seq DAY) <= '2024-12-31' ) AS dates JOIN yonghu ON 1=1;