我得到如下结果
C1 C2 C3
10 2 T
10 3 E
10 6 S
我希望我的SELECT查询以这样的方式生成结果记录看起来像
C1 C2 C3
10 2 T
10 3 E
10 4
10 5
10 6 S
其中缺少记录的空白行。无法找出相同的答案。
原始查询:select C1, C2,C3 from Table
答案 0 :(得分:1)
如果您的mysql版本高于8.0,则可以尝试使用cte RECURSIVE创建日历表,然后执行outer join
模式(MySQL v8.0)
CREATE TABLE T(
C1 int,
C2 int,
C3 varchar(5)
);
INSERT INTO T VALUES (10,2,'T');
INSERT INTO T VALUES (10,3,'E');
INSERT INTO T VALUES (10,6,'S');
查询#1
WITH RECURSIVE CTE AS (
SELECT C1,MIN(C2) minC2,MAX(C2) maxC2
FROM T
GROUP BY C1
UNION ALL
SELECT C1,minC2 +1,maxC2
FROM CTE
WHERE minC2+1 <= maxC2
)
SELECT t1.C1,t1.minC2,t2.C3
FROM CTE t1 LEFT JOIN T t2 on t1.minC2 = t2.C2
ORDER BY C1,minC2;
| C1 | minC2 | C3 |
| --- | ----- | --- |
| 10 | 2 | T |
| 10 | 3 | E |
| 10 | 4 | |
| 10 | 5 | |
| 10 | 6 | S |
答案 1 :(得分:0)
您可以在数据库中创建一个序列号表,然后使用外部联接来填写C2缺少的行值。 它对于其他查询也将非常有用,并且只占用很少的空间。
CREATE TABLE Numbers (Number INTEGER PRIMARY KEY);
INSERT INTO Numbers (Number) VALUES (1),(2),(3),(4),(5),(6) ...
然后:
SELECT T.C1, N.Number AS C2, T.C3
FROM Numbers AS N LEFT OUTER JOIN T ON T.C2 = N.Number
WHERE N.Number BETWEEN (SELECT MIN(C2) FROM T) AND (SELECT MAX(C2) FROM T)
ORDER BY C2;
HTH