在mysql视图中将列合并为单个列

时间:2019-07-08 07:50:10

标签: mysql

如何以这种方式将多个列合并到mysql视图中的单个列中? 我可以得到帮助吗?

                        Source Table
+-----+------------+------------+------------+------------+
|  id |  column1   |  column2   |  column3   |  column4   |
+-----+------------+------------+------------+------------+
|  1  |   value1   |   value2   |   value4   |   value5   |
+-----+------------+------------+------------+------------+
|  2  |   value4   |   value7   |   value5   |   value9   |
+-----+------------+------------+------------+------------+

目标视图

+-----+-----------+
|  id |  columns  |
+-----+-----------+
|  1  |   value1  |
+-----+-----------+
|  1  |   value2  |
+-----+-----------+
|  1  |   value4  |
+-----+-----------+
|  1  |   value5  |
+-----+-----------+
|  2  |   value4  |
+-----+-----------+
|  2  |   value7  |
+-----+-----------+
|  2  |   value5  |
+-----+-----------+
|  2  |   value9  |
+-----+-----------+

这是我尝试过的:

CREATE VIEW viewtb AS
select id, Concat(column1, column2, column3, column4) as columns from maintb;

显然,这没有给我想要的结果。 请注意,在上面的示例表中合并列时,也会重复相应的ID。如何在mysql中获得此结果?谢谢。

2 个答案:

答案 0 :(得分:4)

使用# Navigate to a directory and initiate a local repository git init # Add remote repository to be tracked for changes: git remote add origin https://github.com/username/repository_name.git # Track all changes made on above remote repository # This will show files on remote repository not available on local repository git fetch # Add file present in staging area for checkout git check origin/master -m /path/to/file # NOTE: /path/to/file is a relative path from repository_name git add /path/to/file # Verify track of file(s) being committed to local repository git status # Commit to local repository git commit -m "commit message" # You may perform a final check of the staging area again with git status

union

答案 1 :(得分:1)

SELECT COLUMN1 FROM TABLE_NAME

UNION ALL SELECT COLUMN2 FROM TABLE_NAME

UNION ALL SELECT COLUMN3 FROM TABLE_NAME

但是问题是为什么您会需要它?您可以一次获取该行并使用值,如果需要在表之间建立关系,则可以使用临时表将获取的列存储为行。您需要使用pivot-columns-rows概念