Selecting Columns Starting with a Wildcard
Using wildcards to select specific columns can prove challenging when dealing with similar column names. To retrieve columns based on their starting word, follow these steps:
Creating the SQL Query Dynamically
As seen in the example provided, selecting data using the following query:
<code class="php">$Food = "Vegetable"; mysql_query("SELECT `" . $Food . " %` FROM `Foods`");</code>
will not yield the desired results. Instead, build the SQL query dynamically to obtain the desired column names:
<code class="sql">SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'Foods' AND table_schema = 'YourDB' AND column_name LIKE 'Vegetable%'</code>
This query will return the column names starting with the specified word ("Vegetable" in the example). Remember to replace 'Foods' and 'YourDB' with the actual table name and database schema.
Once you have the column names, use them to construct the SELECT statement and retrieve the data from the specific columns."
The above is the detailed content of How to Select Columns Starting with a Specific Word Using Wildcards in SQL?. For more information, please follow other related articles on the PHP Chinese website!