Home >Database >Mysql Tutorial >How Can I Select Data from Columns with Similar Prefixes in a SQL Database?
Extracting Data from Columns with Similar Prefixes
As database users often encounter tables with numerous columns sharing similar naming conventions, extracting specific data based on these prefixes can be challenging. Consider a table with columns like "Vegetable_Name," "Fruit_Name," and "Meat_Name."
In attempting to select all information related to a specific food group, a user tried:
<code class="sql">$Food = "Vegetable"; mysql_query("SELECT `" . $Food . "%` FROM `Foods`");</code>
However, this query proved ineffective. To address this issue, it is necessary to dynamically construct the SQL query based on the desired prefix.
Dynamic SQL Query Generation
To retrieve the desired columns, follow these steps:
<code class="sql">SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'Foods' AND table_schema = 'YourDB' AND column_name LIKE 'Vegetable%'</code>
Example:
Assume the retrieved column names are "Vegetable_Name" and "Vegetable_Type." The following query would select data from these columns:
<code class="sql">SELECT Vegetable_Name, Vegetable_Type FROM Foods</code>
This approach allows for efficient and targeted data retrieval, even for tables with multiple columns sharing similar prefixes.
The above is the detailed content of How Can I Select Data from Columns with Similar Prefixes in a SQL Database?. For more information, please follow other related articles on the PHP Chinese website!