MySQL - Subquery in SELECT clause

耗尽温柔 提交于 2019-12-11 17:27:09

问题


I am trying to use the results of a query in the SELECT clause.

I query the information_schema to get the column names to select. I then use CONCAT and GROUP_CONCAT to format the results into the following form:

table1.column1,table1.column2,table1.column3,table1.column4

Here is the statement:

SELECT Group_concat(DISTINCT Concat("table1.", column_name)) 
FROM   information_schema.columns 
WHERE  table_name = "table1";

Now, I would like to use these results in a query like this:

SELECT (SELECT Group_concat(DISTINCT Concat("table1.", column_name)) 
        FROM   information_schema.columns 
        WHERE  table_name = "table1") 
FROM   table1;

This incorrectly returns the following results:

+-----------------------------------------------------------------------------------------------------------------------------+
| (SELECT Group_concat(DISTINCT Concat("table1.", column_name)) FROM information_schema.columns WHERE  table_name = "table1") |
+-----------------------------------------------------------------------------------------------------------------------------+
| table1.column1,table1.column2,table1.column3,table1.column4                                                                 |
| table1.column1,table1.column2,table1.column3,table1.column4                                                                 |
| table1.column1,table1.column2,table1.column3,table1.column4                                                                 |
+-----------------------------------------------------------------------------------------------------------------------------+

Where it should return results similar to the results of:

SELECT * FROM table1;

It seems like this person managed to get it working, but I was unable to find my error from that question.

Note: I want to do this to eventually have a script that can dynamically JOIN tables where the table names are only known at runtime, in order to report all data that is affected by a single change.

来源:https://stackoverflow.com/questions/29628296/mysql-subquery-in-select-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!