如果满足给定条件,则选择两列,否则选择另外两列

时间:2017-09-11 09:56:33

标签: mysql

我有以下mysql查询

mysql> SELECT COUNT(*) AS freq, column_name FROM table_name WHERE created_time >= CURDATE() GROUP BY column_name;
Empty set (0.41 sec)

在这种情况下,当结果为空时,我想为两列返回0,所以结果应为:

+--------+------------+
| freq   | column_name|
+--------+------------+
|      0 |       0    |
+--------+------------+

我尝试了以下方法,但没有一个按预期工作:

mysql> SELECT IFNULL(COUNT(*) AS freq, 0), IFNULL(column_name, 0) FROM table_name WHERE created_time >= CURDATE() GROUP BY column_name;
Empty set (0.40 sec)


mysql> SELECT IFNULL((SELECT COUNT(*), column_name FROM table_name WHERE created_time >= CURDATE() GROUP BY column_name), 'not found');
ERROR 1241 (21000): Operand should contain 1 column(s)


mysql> SELECT CASE WHEN ( (SELECT COUNT(*) FROM table_name WHERE created_time >= CURDATE()) > 0 )
            THEN (SELECT COUNT(*) AS freq, column_name FROM table_name WHERE created_time >= CURDATE() GROUP BY column_name)
            ELSE (SELECT 0,0) END;
ERROR 1241 (21000): Operand should contain 1 column(s)


mysql> SELECT IF(
    (SELECT COUNT(*) FROM table_name WHERE created_time >= CURDATE()) > 0,
    (SELECT COUNT(*) AS freq, column_name FROM table_name WHERE created_time >= CURDATE() GROUP BY column_name),
    (SELECT 0,0)
    );
ERROR 1241 (21000): Operand should contain 1 column(s)

我做错了什么?感谢

1 个答案:

答案 0 :(得分:0)

作为解决方法,您可以使用union的技巧:

SELECT COUNT(*) AS freq, column_name 
FROM table_name 
WHERE created_time >= CURDATE() 
GROUP BY column_name
UNION
SELECT 0,0
FROM dual
WHERE (SELECT COUNT(*) FROM table_name WHERE created_time >= CURDATE()) = 0

我希望有人建议更优雅的方式来做到这一点