Home > Database > Mysql Tutorial > body text

How to Select Data from Columns with Similar Prefixes using Dynamic SQL in MySQL?

Linda Hamilton
Release: 2024-11-03 08:38:02
Original
1000 people have browsed it

How to Select Data from Columns with Similar Prefixes using Dynamic SQL in MySQL?

Dynamic SQL for Wildcard Column Selection

Question:

Suppose you have a database table with multiple columns sharing similar prefixes, such as "Fruit" and "Vegetable." How can you efficiently select data from all columns starting with a specific word without manually specifying each column name?

Example:

Consider the following table structure:

<code class="markdown">Foods | Fruit | Vegetable
----------------------
Apples | Banana | Carrots
Pears | Grapes | Potatoes
Oranges | Lemon | Tomatoes</code>
Copy after login

You wish to select all columns whose names start with "Vegetable."

Answer:

Direct wildcard substitutions in MySQL queries, such as SELECT Vegetable %, are not supported. To dynamically select all columns meeting this criteria, you can build the SQL query based on information obtained from the database schema. Here's a solution:

<code class="sql">SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Foods'
  AND table_schema = 'YourDB'
  AND column_name LIKE 'Vegetable%'</code>
Copy after login

This query retrieves the names of all columns in the Foods table starting with "Vegetable." You can then use this information to dynamically construct a second query that selects data from the desired columns:

<code class="php">$columnList = mysql_query($columnsQuery);
$columnArray = array();
while ($row = mysql_fetch_assoc($columnList)) {
  array_push($columnArray, $row['COLUMN_NAME']);
}
$columns = implode(",", $columnArray);

$query = "SELECT " . $columns . " FROM Foods";</code>
Copy after login

By executing this query, you can retrieve all data from the columns whose names start with "Vegetable" in a single pass.

The above is the detailed content of How to Select Data from Columns with Similar Prefixes using Dynamic SQL in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template