Selecting all columns that start with XXX using a wildcard?

混江龙づ霸主 提交于 2019-12-28 01:26:29

问题


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:

I tried selecting all info for a particular thing (food kind in this example) using

$Food = "Vegetable"; 
mysql_query("SELECT `" . $Food . " %` FROM `Foods`");

but it didn't seem to work.

Any help would be appreciated :-)

EDIT: Apparently this wasn't clear from my example, but I already know all column's first words. The columns are always the same and no 'food kinds' are ever added or deleted. The PHP variable is only there to determine which one of a couple of set kinds I need.


回答1:


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?




回答2:


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%'



回答3:


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!"




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/4797686/selecting-all-columns-that-start-with-xxx-using-a-wildcard

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