Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

database - MySQL concatenating all columns

Why can we not concatenate in MySQL using the * keyword?

SELECT concat(*) FROM table

or

SELECT group_concat(*) FROM table

Is there any other way we could access values in a column without explicitly using the columns name?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To concatenate all columns in a table, you can't use the * keyword, but you need to explicitly list all columns:

SELECT CONCAT(col1, col2, col3, ....)
FROM yourtable

or you might want to use CONCAT_WS that will skip null values:

SELECT CONCAT_WS(',', col1, col2, col3, ....)
FROM yourtable

If you don't want to specify all column names manually, you could use a dinamic query. This query will return all column names of your table:

SELECT `column_name` 
FROM   `information_schema`.`columns` 
WHERE  `table_schema`=DATABASE() 
       AND `table_name`='yourtable';

and using GROUP_CONCAT you can obtain a list of all column names:

GROUP_CONCAT(CONCAT('`', column_name, '`'))

quoted, in a comma separated format:

`col1`,`col2`,`col3`,`col4`,...

so now we have all the elements to create our query dinamically:

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;

this query will set the @sql string to something like:

SELECT CONCAT_WS('', col1, col2, col3, ....) AS all_columns FROM yourtable

and this code will execute it:

PREPARE stmt FROM @sql;
EXECUTE stmt;

Please see fiddle here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...