Home >Database >Mysql Tutorial >How to Select Columns Starting with a Specific Word Using Wildcards in SQL?

How to Select Columns Starting with a Specific Word Using Wildcards in SQL?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 17:31:30960browse

How to Select Columns Starting with a Specific Word Using Wildcards in SQL?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn