Home > Database > Mysql Tutorial > body text

How to Concatenate All Columns in a MySQL Table?

Mary-Kate Olsen
Release: 2024-10-24 17:29:02
Original
923 people have browsed it

How to Concatenate All Columns in a MySQL Table?

Concatenating All Columns in MySQL

In MySQL, the * wildcard keyword cannot be used in the CONCAT() function to concatenate all columns in a table. Instead, you must explicitly list each column name:

<code class="sql">SELECT CONCAT(col1, col2, col3, ...)
FROM yourtable;</code>
Copy after login

Alternatively, you can use the CONCAT_WS() function to skip null values:

<code class="sql">SELECT CONCAT_WS(',', col1, col2, col3, ...)
FROM yourtable;</code>
Copy after login

If you prefer, you can avoid manually specifying column names by utilizing a dynamic query. Retrieve the column names of your table:

<code class="sql">SELECT `column_name`
FROM `information_schema`.`columns`
WHERE `table_schema` = DATABASE()
AND `table_name` = 'yourtable';</code>
Copy after login

Use GROUP_CONCAT to obtain a comma-separated list of column names:

<code class="sql">GROUP_CONCAT(CONCAT('`', column_name, '`'))</code>
Copy after login

Now, build your dynamic query by concatenating elements:

<code class="sql">SELECT
CONCAT(
'SELECT CONCAT_WS(\'\',',
GROUP_CONCAT(CONCAT('`', column_name, '`') ORDER BY column_name),
') AS all_columns FROM yourtable;')
FROM `information_schema`.`columns`
WHERE `table_schema` = DATABASE()
AND `table_name` = 'yourtable'
INTO @sql;</code>
Copy after login

This query will set the @sql variable to a string similar to:

<code class="sql">SELECT CONCAT_WS('', col1, col2, col3, ...) AS all_columns FROM yourtable;</code>
Copy after login

Finally, execute this dynamic query:

<code class="sql">PREPARE stmt FROM @sql;
EXECUTE stmt;</code>
Copy after login

For an example with a SQLfiddle, consult the provided HTML source.

The above is the detailed content of How to Concatenate All Columns in a MySQL Table?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!