我有一个具有以下架构的MariaDB表:
+-------------------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+---------------------+------+-----+---------+-------+
| id | int(10) unsigned | NO | PRI | 0 | |
| date | date | NO | PRI | NULL | |
| HE | tinyint(3) unsigned | NO | PRI | 0 | |
| minute | tinyint(3) unsigned | NO | PRI | 0 | |
| price | float | NO | | NULL | |
+-------------------+---------------------+------+-----+---------+-------+
该表包含五分钟间隔的价格(1-24小时和0-55分钟)。没有价格的间隔没有行。我正在尝试编写一个查询来填充零值的缺失间隔,而不是简单地在其中写入包含该信息的行。
我尝试使用间隔为24小时5分钟的子查询,并将其连接到he和minutes列,但没有成功。
我在下面尝试过的代码。子查询正确返回1-24小时和5分钟间隔0-55,但是最终结果仅包括价格表中填充的行,而不是整个时间序列。我本以为右连接应该做到这一点,但是我也尝试了内连接,左连接和不成功的连接。
select B.id, B.date, A.he, A.minute, B.price
from price B
right join (select distinct he, minute from price where id = 4093739409 and minute % 5 = 0 order by he,minute) as A
on B.he = A.he and B.minute = A.minute
where B.date = '2019-04-18' and B.id = 4093739409;
答案 0 :(得分:1)
代替从数据中 的小时和分钟列表的外部联接,构建 所有小时-分钟组合的列表和外部联接:
SELECT x1.he, x2.minute, price.*
FROM (
SELECT 01 AS he UNION ALL
SELECT 02 UNION ALL
...
SELECT 24
) AS x1
CROSS JOIN (
SELECT 00 AS minute UNION ALL
SELECT 05 UNION ALL
...
SELECT 55
) AS x2
LEFT JOIN price ON x1.he = price.he AND x2.minute = price.minute AND price.date = '2019-04-18' AND price.id = 4093739409
ORDER BY x1.he, x2.minute
在MariaDB中,您也许可以使用行值构造函数,即(VALUES (01), (02), ..., (24)) AS x1(he)
。