简体   繁体   中英

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

Can anyone tell me how I can use a result from a CONCAT as a column name 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 column 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.

Thanks for your help.

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;

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM