从tableB插入tableA,其中条件设置为case

时间:2015-10-27 17:32:08

标签: mysql insert set

  

第一个问题:

我正在尝试从tableB中插入tableA字段,其中我有条件并为columnA设置一个大小写,但它不起作用。没有UPDATE可以做到吗?

insert into tableA
select date, columnA 
from tableB
where tableB.date between '2015-10-01' and '2015-10-31'
set columnA = case
              when columnA like ('%aaa%') then 'aaa'
              when columnA like ('%bbb%') then 'bbb'
              when columnA like ('%ccc%') then 'ccc'
              when columnA like ('%ddd%') then 'ddd'
              when columnA like ('%eee%') then 'eee'
              else columnA 
              end
;

wchiquito 回复说它有效。

  

第二个问题:

此外,我希望看到第一个问题的解决方案,以防我分组日期和列A.

我可以这样做:

insert into tableA
select date, case
              when columnA like ('%aaa%') then 'aaa'
              when columnA like ('%bbb%') then 'bbb'
              when columnA like ('%ccc%') then 'ccc'
              when columnA like ('%ddd%') then 'ddd'
              when columnA like ('%eee%') then 'eee'
              else columnA 
              end
from tableB
where tableB.date between '2015-10-01' and '2015-10-31'
group by date, case
              when columnA like ('%aaa%') then 'aaa'
              when columnA like ('%bbb%') then 'bbb'
              when columnA like ('%ccc%') then 'ccc'
              when columnA like ('%ddd%') then 'ddd'
              when columnA like ('%eee%') then 'eee'
              else columnA 
              end
;

但我想知道是否还有另一种方式。避免双重写案件的更好方法。

1 个答案:

答案 0 :(得分:1)

请注意,column是保留字,请参阅9.3 Keywords and Reserved Words

请参阅12.4 Control Flow Functions - CASE

INSERT INTO `tableA`
SELECT `date`, CASE
                WHEN `column` LIKE '%aaa%' THEN 'aaa'
                WHEN `column` LIKE '%bbb%' THEN 'bbb'
                WHEN `column` LIKE '%ccc%' THEN 'ccc'
                WHEN `column` LIKE '%ddd%' THEN 'ddd'
                WHEN `column` LIKE '%eee%' THEN 'eee'
                ELSE `column`
              END
FROM `tableB`
WHERE `tableB`.`date` BETWEEN '2015-01-01' AND '2015-01-04';

SQL Fiddle demo