Home > Database > Mysql Tutorial > How to Select Columns Dynamically Based on a Wildcarded Prefix in MySQL?

How to Select Columns Dynamically Based on a Wildcarded Prefix in MySQL?

DDD
Release: 2024-11-04 04:44:29
Original
931 people have browsed it

How to Select Columns Dynamically Based on a Wildcarded Prefix in MySQL?

Dynamically Selecting Columns Based on a Wildcarded Prefix

Within a database, one may encounter situations where they need to select specific columns based on a shared prefix in their names. While the provided MySQL query attempt with a wildcard does not work, there is a solution involving dynamically generating the SQL.

To retrieve column names that start with a particular prefix, one can leverage the following SQL query:

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Foods'
    AND table_schema = 'YourDB'
    AND column_name LIKE 'Vegetable%'
Copy after login

In this query, 'Foods' represents the table name, 'YourDB' is the database schema, and 'Vegetable' is the desired column prefix. Replace these values with your specific table, schema, and prefix.

Once the column names are obtained, you can dynamically construct a query to select the corresponding data. For example:

SELECT `VegetableName1`, `VegetableName2`, `VegetableName3`
FROM `Foods`
Copy after login

Here, assume the column names obtained are 'VegetableName1', 'VegetableName2', and 'VegetableName3'. Replace these names with the ones derived from the above INFORMATION_SCHEMA query.

By employing this approach, you can effectively select specific columns based on their shared wildcard prefix. This technique is useful when working with databases where column names follow consistent naming conventions.

The above is the detailed content of How to Select Columns Dynamically Based on a Wildcarded Prefix 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template