How can I use CONCAT during SELECT in MySQL as a collumnname?

这一生的挚爱 提交于 2019-12-25 00:47:47

问题


Can anyone tell me how I can use a result from a CONCAT as a columnname during SELECT? My attempt looks like this:

INSERT INTO `table_1` (datum, comment)
SELECT CURRENT_DATE(), CONCAT('s',DAYOFWEEK(CURRENT_DATE())-1)
FROM `table_2` WHERE id = 12345

As a result I get s0 - s6 as a value in my comment field instead of the value that is actually in my 2nd table that I want to read the value from :/

funfact: If I just type in s0 (as an example, works with all 7) instead of the CONCAT, it works just fine and I get the actual value that I want to.

Thx for your help.


回答1:


Well, I must admit it took me a while to understand what you are asking. Table2 has 7 columns s0 to s6 and you want to get the value from the column matching the date. Yes?

So, of course using

SELECT CURRENT_DATE(), s2

gives you the content of s2, whereas

SELECT CURRENT_DATE(), CONCAT('s',DAYOFWEEK(CURRENT_DATE())-1)

gives you 's2'. It would be horrible if not. Are you really expecting the DBMS to calculate a value and then check whether that value happens to match a column name? Then

select name, job from person;

would select the person's name and job in most cases but for the person named Job you would get the job twice instead. You see that this can not be desired, right?

So check your expression result instead and read from the according column:

insert into table_1 (datum, comment)
select 
  current_date(), 
  case dayofweek(current_date()) - 1 
    when 0 then s0
    when 1 then s1
    when 2 then s2
    when 3 then s3
    when 4 then s4
    when 5 then s5
    when 6 then s6
  end
from table_2 where id = 12345;



回答2:


You can use like this

INSERT INTO `table_1` (datum, comment)
SELECT CURRENT_DATE(), 
CASE DAYOFWEEK(CURRENT_DATE())-1
 WHEN 0 THEN s0
 WHEN 1 THEN s1
 WHEN 2 THEN s2
 WHEN 3 THEN s3
 WHEN 4 THEN s4
 WHEN 5 THEN s5
 WHEN 6 THEN s6
 END
FROM `table_2` WHERE id = 12345 


来源:https://stackoverflow.com/questions/32821524/how-can-i-use-concat-during-select-in-mysql-as-a-collumnname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!