mysql:0 而不是空 table
mysql: 0 instead of an empty table
我有一个 sql 查询(简化示例):
select
ifnull(count(table.id), 0) as count
from
table
where
table.id > 10000
如果 table 中的任何内容都没有找到,结果它显示一个空的 table,但我想输出 0。
如何做到这一点?
我的决定(速度下降了5倍!!!)
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;
成功了!但是很慢:(
对不起,速度是恒定的:)我的错误
结果:
使用 SQL_CALC_FOUND_ROWS 和 FOUND_ROWS 解决了问题(感谢@Unknown User)
但暂时 tables... 不确定这种决定的最优性
您可以使用这个查询。这将为您提供匹配查询的记录总数。如果没有匹配结果,那么它会给你 0
.
SELECT SQL_CALC_FOUND_ROWS ColumnName FROM TableName WHERE ColumnName IN ('');
SELECT FOUND_ROWS();
这样:
select
COALESCE(count(table.id), 0) as count
from
table
where
table.id > 10000
group by table.id
您可以使用 case when 检查 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
只需删除 group by
。此外,ifnull()
是不必要的:
select count(t.id) as `count`
from table t
where t.id > 10000;
你好像想要满足条件的id的个数。您的版本会 return 每个 id
.
单独计数
如果您想对每个 id
进行单独计数,您可以这样做:
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);
我有一个 sql 查询(简化示例):
select
ifnull(count(table.id), 0) as count
from
table
where
table.id > 10000
如果 table 中的任何内容都没有找到,结果它显示一个空的 table,但我想输出 0。
如何做到这一点?
我的决定(速度下降了5倍!!!)
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;
成功了!但是很慢:(
对不起,速度是恒定的:)我的错误
结果: 使用 SQL_CALC_FOUND_ROWS 和 FOUND_ROWS 解决了问题(感谢@Unknown User) 但暂时 tables... 不确定这种决定的最优性
您可以使用这个查询。这将为您提供匹配查询的记录总数。如果没有匹配结果,那么它会给你 0
.
SELECT SQL_CALC_FOUND_ROWS ColumnName FROM TableName WHERE ColumnName IN ('');
SELECT FOUND_ROWS();
这样:
select
COALESCE(count(table.id), 0) as count
from
table
where
table.id > 10000
group by table.id
您可以使用 case when 检查 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
只需删除 group by
。此外,ifnull()
是不必要的:
select count(t.id) as `count`
from table t
where t.id > 10000;
你好像想要满足条件的id的个数。您的版本会 return 每个 id
.
如果您想对每个 id
进行单独计数,您可以这样做:
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);