请帮助我理解为什么以下两个查询会返回不同的结果。查询的区别仅在于使用GROUP BY子句中的DATE_FORMAT函数。
查询1:
SELECT DATE_FORMAT(T0.ET,'%Y/%m/%d %H%i'), SUM(T0.AT)
FROM(SELECT TIMESTAMPADD(second,(SEQ -1)*300, STR_TO_DATE('20170809135000','%Y%m%d%H%i%s')) ET, 1 AT
FROM SEQ_1_TO_10
WHERE SEQ <= 5) T0
group by T0.ET with rollup
结果1:
'2017/08/09 1350', '1'
'2017/08/09 1355', '1'
'2017/08/09 1400', '1'
'2017/08/09 1405', '1'
'2017/08/09 1410', '1'
NULL, '5'
查询2:
SELECT DATE_FORMAT(T0.ET,'%Y/%m/%d %H%i') , SUM(T0.AT)
FROM(SELECT TIMESTAMPADD(second,(SEQ -1)*300, STR_TO_DATE('20170809135000','%Y%m%d%H%i%s')) ET, 1 AT
FROM SEQ_1_TO_10
WHERE SEQ <= 5) T0
group by DATE_FORMAT(T0.ET,'%Y/%m/%d %H%i') with rollup
结果2:
'2017/08/09 1350', '1'
'2017/08/09 1355', '1'
'2017/08/09 1400', '1'
'2017/08/09 1405', '1'
'2017/08/09 1410', '1'
'2017/08/09 1410', '5'
两个查询的EXPLAIN SELECT都是相同的:
id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
'1', 'SIMPLE', 'SEQ_1_TO_10', 'range', 'PRIMARY', 'PRIMARY','8', NULL, '5', 'Using where; Using index; Using filesort'
答案 0 :(得分:1)
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 13
Server version: 10.1.14-MariaDB mariadb.org binary distribution
Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [sandbox]> SELECT typ ,DATE_FORMAT(T.ET,'%Y/%m/%d %H%i') et, sum(1)
-> FROM(
-> SELECT TIMESTAMPADD(second,(SEQ -1)*300, STR_TO_DATE('20170809135000','%Y%m%d%H%i%s')) ET,
-> case when seq % 2 = 0 then 'a' else 'b' end as typ
-> FROM SEQ_1_TO_10
-> WHERE SEQ <= 5
-> ) T
-> group by typ,DATE_FORMAT(T.ET,'%Y/%m/%d %H%i') with rollup;
+------+-----------------+--------+
| typ | et | sum(1) |
+------+-----------------+--------+
| a | 2017/08/09 1355 | 1 |
| a | 2017/08/09 1405 | 1 |
| a | 2017/08/09 1405 | 2 |
| b | 2017/08/09 1350 | 1 |
| b | 2017/08/09 1400 | 1 |
| b | 2017/08/09 1410 | 1 |
| b | 2017/08/09 1410 | 3 |
| NULL | 2017/08/09 1410 | 5 |
+------+-----------------+--------+
8 rows in set (0.00 sec)