MySQL能否将这段代码换一下方式
时间: 2024-03-26 22:39:51 浏览: 63
修改mysql编码的一种方法
可以的,可以将这个查询语句拆分成多个子查询,然后使用 MySQL 的 WITH 语句或者临时表来进行连接。
以下是使用临时表的方式进行查询:
```
CREATE TEMPORARY TABLE IF NOT EXISTS a (
datatime VARCHAR(10),
sortnum INT
);
INSERT INTO a (datatime, sortnum)
SELECT DATE_FORMAT(NOW() ,"%Y-%m-%d"), 1 AS sortnum
UNION ALL
SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 DAY) ,"%Y-%m-%d"), 2 AS sortnum
UNION ALL
SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 2 DAY) ,"%Y-%m-%d"), 3 AS sortnum
UNION ALL
SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 3 DAY) ,"%Y-%m-%d"), 4 AS sortnum
UNION ALL
SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 4 DAY) ,"%Y-%m-%d"), 5 AS sortnum
UNION ALL
SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 5 DAY) ,"%Y-%m-%d"), 6 AS sortnum
UNION ALL
SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 6 DAY) ,"%Y-%m-%d"), 7 AS sortnum;
CREATE TEMPORARY TABLE IF NOT EXISTS b (
GET_DATE DATETIME,
TAG_VALUE INT
);
INSERT INTO b (GET_DATE, TAG_VALUE)
SELECT GET_DATE, TAG_VALUE
FROM T_TAG_DATA
WHERE TAG_ID = 1408;
CREATE TEMPORARY TABLE IF NOT EXISTS c (
datatime VARCHAR(10),
当日产量 INT
);
INSERT INTO c (datatime, 当日产量)
SELECT a.datatime, IFNULL(SUM(b.TAG_VALUE), 0) AS 当日产量
FROM a
LEFT JOIN b ON a.datatime = DATE_FORMAT(b.GET_DATE, "%Y-%m-%d")
GROUP BY a.datatime;
CREATE TEMPORARY TABLE IF NOT EXISTS d (
datatime VARCHAR(10),
台时产量 INT
);
INSERT INTO d (datatime, 台时产量)
SELECT a.datatime, IFNULL(b.TAG_VALUE, 0) AS 台时产量
FROM a
LEFT JOIN b ON a.datatime = DATE_FORMAT(b.GET_DATE, "%Y-%m-%d")
WHERE DATE_FORMAT(NOW(), "%H:%i") = DATE_FORMAT(b.GET_DATE, "%H:%i");
CREATE TEMPORARY TABLE IF NOT EXISTS e (
datatime VARCHAR(10),
累计产量 INT
);
INSERT INTO e (datatime, 累计产量)
SELECT DATE_FORMAT(GET_DATE, "%Y-%m-%d") AS datatime, SUM(TAG_VALUE) AS 累计产量
FROM b
WHERE GET_DATE BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
GROUP BY datatime;
SELECT SUBSTRING(a.datatime, 6, 10) AS datatime, IFNULL(c.当日产量, 0) AS 当日产量, IFNULL(d.台时产量, 0) AS 台时产量, IFNULL(e.累计产量, 0) AS 累计产量
FROM a
LEFT JOIN c ON a.datatime = c.datatime
LEFT JOIN d ON a.datatime = d.datatime
LEFT JOIN e ON a.datatime = e.datatime
ORDER BY a.datatime ASC;
```
这里先创建了临时表 a, b, c, d, e,然后分别对应原来的子查询。最后对 a, c, d, e 四个临时表进行 left join,生成最终的查询结果。
阅读全文