Selecting all columns that start with XXX using a wildcard?

前端 未结 5 2278
一生所求
一生所求 2020-11-29 10:58

I have several columns in my databases with similar names. How do I select those based on the word they start with? Here\'s an example table layout:

5条回答
  •  半阙折子戏
    2020-11-29 11:33

    Here's a way I did it purely with MySQL:

    SET SESSION group_concat_max_len = 2048;
    SELECT GROUP_CONCAT(CONCAT(" ",CAST(column_name as CHAR(50)))) FROM information_schema.columns WHERE table_name='real_big_table' AND column_name LIKE 'prefix%' INTO @sub;
    SET @x = CONCAT("SELECT ",@sub," FROM my_db.real_big_table WHERE my_db.real_big_table.country_id='US'");
    PREPARE stmt FROM @x;
    EXECUTE stmt;
    

    My answer is inspired by this answer.

    Note: My 'inner-DBA' (in the form of a small angel on my shoulder) tells me that needing to do this is probably a sign of bad DB structure, but my 'inner-hacker' (in the form of a small devil on my other shoulder) says "just get it done!"

提交回复
热议问题