如果不满足特定条件,如何获得空集

时间:2017-03-10 07:09:50

标签: mysql sql where

以下查询工作正常,但问题是,它总是返回一个结果。它永远不会返回一个空集。

SELECT sum(vmin_consumed) AS vmin
FROM usageinfo
WHERE job_end_time BETWEEN '2017-03-14' AND '2017-03-30'
AND username='tytyjt'

如果未满足任何条件,则返回NULL。如果不满足第二个条件(username='foo'),我可以使上面的查询返回空结果集吗?

4 个答案:

答案 0 :(得分:1)

试试这个:

SELECT p.* FROM (SELECT sum(vmin_consumed) AS vmin, username
FROM usageinfo
WHERE job_end_time BETWEEN '2017-03-14' AND '2017-03-30' AND username = "foo") p where p.username = "foo"

答案 1 :(得分:0)

你需要这个,

SELECT IFNULL(SUM(vmin_consumed), '') AS vmin
FROM usageinfo
WHERE job_end_time BETWEEN '2017-03-14' AND '2017-03-30'
AND username='tytyjt'

答案 2 :(得分:0)

这真是一个奇怪的要求,试试这个:

SELECT
    SUM(
        CASE WHEN job_end_time BETWEEN '2017-03-14' AND '2017-03-30' THEN vmin_consumed -- The first condition is here.
             ELSE null 
        END) AS vmin
FROM usageinfo
GROUP BY username
HAVING username = 'tytyjt' -- The second condition is here.

我必须承认,当您拥有大数据时,这会导致性能问题。

答案 3 :(得分:0)

试试这个:

SELECT _TABLE.VMIN FROM (SELECT SUM(vmin_consumed) AS VMIN
FROM usageinfo
WHERE job_end_time BETWEEN '2017-03-14' AND '2017-03-30' AND _TABLE.username =   'tytyjt') 
_TABLE
WHERE _TABLE.VMIN IS NOT NULL