MYSQL~~~ 数据库若查出了没有数据(数据条数为0) ,强制加一条默认值的方法

  • Post author:
  • Post category:mysql




数据库若查出了没有数据(数据条数为0) ,强制加一条默认值的方法




方法一



创建临时表

drop TABLE  IF EXISTS temporary_table;
CREATE TEMPORARY TABLE temporary_table AS
(SELECT '默认' as a ,'默认' as b);
select  
classId,
className
from class
where className='21212'
union all
select * from temporary_table;



思路:创建临时表,将临时表中,加入数据。通过union all将需要查的表和临时表进行合并,得到一有原表无数据,但是数据集有默认值的效果

在这里插入图片描述



** 方法二**



使用case when 加count

SELECT 
CASE  WHEN  count(classId)>0 THEN 
if (classId is not null and classId <> '' ,classId, 4) 
else 4 END as 'a'
from class 
where className='21212'


思路:通过查询结果个数,判断,如果count个数为0,那么给字段复制一个默认值



版权声明:本文为weixin_50235904原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。