Reputation: 1428
I have a sql query (simplified example):
select
ifnull(count(table.id), 0) as count
from
table
where
table.id > 10000
If anything in the table was not found, as a result it displays an empty table, but I want to output 0.
my decision (speed has decreased in 5 times!!!)
DROP TEMPORARY TABLE IF EXISTS xxx;
CREATE TEMPORARY TABLE xxx ENGINE = MEMORY AS (SELECT SQL_CALC_FOUND_ROWS ...);
IF (FOUND_ROWS() = 0) THEN
SELECT 0 AS count;
ELSE
SELECT * FROM xxx;
END IF;
Sorry, speed is constant :) my mistake
results: the problem was solved by the use of SQL_CALC_FOUND_ROWS and FOUND_ROWS (thanks @Unknown User) but temporary tables... not sure about the optimality of such a decision
Upvotes: 0
Views: 275
Reputation: 1269953
Just remove the group by
. Also, the ifnull()
is unnecessary:
select count(t.id) as `count`
from table t
where t.id > 10000;
You seem to want the count of ids that meet the condition. Your version would return a separate count for each id
.
If you wanted a separate count for each id
, you could do:
select id, count(t.id) as `count`
from table t
where t.id > 10000
group by id
union all
select null, 0
from table t
where not exists (select 1 from table t2 where t2.id > 10000);
Upvotes: 1
Reputation: 31993
you can use case when for checking no value in table
SELECT case when table.id is null then 0
else count(table.id) end as Count_NUM_ID FROM table
where
table.id > 10000
Upvotes: 1
Reputation: 4191
This way:
select
COALESCE(count(table.id), 0) as count
from
table
where
table.id > 10000
group by table.id
Upvotes: 1