Mysql:if else从一列到另一列

时间:2017-02-24 09:42:52

标签: mysql

如果value =' 0'我想知道是否有机会从另一个表中插入表格然后导入='否'否则导入='是'

现在自动开启'是'插入。

我的SQL查询:

insert into table_3 (name, data, type, value, import)
select name_batch, data_of_insert, 'File 2', SUM(value), 'yes'
from table_2
WHERE data_of_insert > DATE_SUB(now(), INTERVAL 1 SECOND)
group by name_batch");

2 个答案:

答案 0 :(得分:1)

您可以使用CASE

insert into table_3 (name, data, type, value, import)
select name_batch, data_of_insert, 'File 2', SUM(value), 
    case when SUM(value) = 0 then 'no' else 'yes' end
from table_2
where data_of_insert > DATE_SUB(now(), INTERVAL 1 SECOND)
group by name_batch

只有在ONLY_FULL_GROUP_BY被禁用时,以上内容才有效。

如果没有,请使用:

insert into table_3 (name, data, type, value, import)
select name_batch, data_of_insert, 'File 2', SUM(value), 
    case when SUM(value) = 0 then 'no' else 'yes' end
from table_2
where data_of_insert > DATE_SUB(now(), INTERVAL 1 SECOND)
group by name_batch, data_of_insert

答案 1 :(得分:0)

检查并告诉我是否有效!。

insert into table_3 (name, data, type, value, import)
select name_batch, data_of_insert, 'File 2', SUM(value), IF(SUM(value)=0, 'no', 'yes') as value
from table_2
WHERE data_of_insert > DATE_SUB(now(), INTERVAL 1 SECOND)
group by name_batch");