我有以下声明:
SELECT DISTINCT Concat("table1.", column_name)
FROM information_schema.columns
WHERE table_name = "table1"
UNION ALL
SELECT DISTINCT Concat("table2.", column_name)
FROM information_schema.columns
WHERE table_name = "table2";
产生以下结果:
+---------------------------------+
| CONCAT("table1.", column_name) |
+---------------------------------+
| table1.column1 |
| table1.column2 |
| table1.column3 |
| table2.column4 |
| table2.column5 |
| table2.column6 |
| table2.column7 |
+---------------------------------+
我希望它采用以下格式:
+-----------------------------------------------------------------------------------------------------------+
| CONCAT("table1.", column_name) |
+-----------------------------------------------------------------------------------------------------------+
| table1.column1,table1.column2,table1.column3,table2.column4,table2.column5,table2.column6,table2.column7 |
+-----------------------------------------------------------------------------------------------------------+
我尝试过这样使用GROUP_CONCAT
:
SELECT Group_Concat(DISTINCT Concat("table1.", column_name))
FROM information_schema.columns
WHERE table_name = "table1"
UNION ALL
SELECT Group_Concat(DISTINCT Concat("table2.", column_name))
FROM information_schema.columns
WHERE table_name = "table2";
但这不正确地产生了以下结果:
+--------------------------------------------------------------+
| CONCAT("table1.", column_name) |
+--------------------------------------------------------------+
| table1.column1,table1.column2,table1.column3 |
| table2.column4,table2.column5,table2.column6,table2.column7 |
+--------------------------------------------------------------+
由此我自然尝试将GROUP_CONCAT
作为子查询,如下所示:
SELECT GROUP_Concat(
SELECT Group_Concat(DISTINCT Concat("table1.", column_name))
FROM information_schema.columns
WHERE table_name = "table1"
UNION ALL
SELECT Group_Concat(DISTINCT Concat("table2.", column_name))
FROM information_schema.columns
WHERE table_name = "table2" t)
FROM t;
但是上面的语句中存在语法错误。我如何将UNION ALL
的结果连接成一行?
我已经审核了以下问题但没有取得任何成功:
Combing results from union all into one row when some columns have different values
How do I combine two queries (union all) into one row?
MySQL COUNT results of UNION ALL statement
这与我之前的问题有关: MySQL - Subquery in SELECT clause
答案 0 :(得分:3)
你几乎就在那里,试试这个:
select group_concat(xxx) from (
SELECT DISTINCT Concat("table1.", column_name) as xxx
FROM columns
WHERE table_name = "table1"
UNION ALL
SELECT DISTINCT Concat("table2.", column_name)
FROM columns
WHERE table_name = "table2"
) as src;
说实话 - 你需要这个UNION
是什么?这样做也会......
SELECT
group_concat(distinct concat (table_name, '.', column_name) )
from columns
WHERE table_name in ('table1', 'table2');
答案 1 :(得分:0)
SELECT GROUP_Concat(a)
FROM (
SELECT Group_Concat(DISTINCT Concat("table1.", column_name)) as a
FROM information_schema.columns
WHERE table_name = "table1"
UNION ALL
SELECT Group_Concat(DISTINCT Concat("table2.", column_name))
FROM information_schema.columns
WHERE table_name = "table2" ) t
GROUP BY 1