Selecting all columns that start with XXX using a wildcard?

前端 未结 5 2187
一生所求
一生所求 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:29

    There's no way to do exactly what you're trying to. You could do another query first to fetch all the column names, then process them in PHP and build the second query, but that's probably more complex than just writing out the names that you want.

    Or is there a reason this query needs to be dynamic? Will the table's structure change often?

    0 讨论(0)
  • 2020-11-29 11:30

    How about creating the query in 2 steps?

    1- Get the column's name from the db schema (or elsewhere)

    2- Generate an sql query with the column's name that match your filter condition.

    0 讨论(0)
  • 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!"

    0 讨论(0)
  • 2020-11-29 11:42

    Convert your database to one with three columns:

    Product_type (vegetable, fruit, etc) 
    
    Name (apple, carrot, etc) 
    
    color (orange, yellow, etc)
    

    Now you can use your wildcard to obtain only a certain type, because it now is IN a columns, not in the header.

    0 讨论(0)
  • 2020-11-29 11:44

    You'd have to build the SQL dynamically. As a starting point, this would get you the column names you're seeking.

    SELECT COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_name = 'Foods'
            AND table_schema = 'YourDB'
            AND column_name LIKE 'Vegetable%'
    
    0 讨论(0)
提交回复
热议问题