数据库
首页 > 数据库> > 如何在MySQL中创建视图以将第二个表中的行合并为第一个CSV列

如何在MySQL中创建视图以将第二个表中的行合并为第一个CSV列

作者:互联网

我需要在MySQL中创建可以将两个表组合在一起的VIEW,以便对于第一个表中的每一行都必须添加第二个表中的列,但是由于行数据必须格式化为具有多个CSV的多个字段,因此每一行必须具有多个CSV.

我最初的方法是使用MySQL VIEW,但无法找到将第二个表中的多行数据显示为View表中的CSV单个单元格数据的方法.

这里有些例子:

1st table: gears
+------------+------------------------+-----------------+
| MainGearID | MainGearName           | MainGearType    |
+------------+------------------------+-----------------+
|          1 | Main Drive             | Spur            |
|          2 | Secondary Drive        | Spur            |
|          3 | Backup Secondary Drive | Hypoid          |
|          4 | AUX Drive              | Rack and pinion |
+------------+------------------------+-----------------+

2nd table: orbitinggears:
+----------+------------+--------------+--------------+
| OrbitaID | MainGearID | OrbitalType  | OrbitalValue |
+----------+------------+--------------+--------------+
|        1 |          1 | Spur         | 112          |
|        2 |          1 | Spur         | 280          |
|        3 |          2 | Spur         | 144          |
|        4 |          2 | Spur         | 248          |
|        5 |          3 | Helical      | 18           |
|        6 |          4 | Spur         | 144          |
+----------+------------+--------------+--------------+

Required View:
+------------+------------------------+-----------------+----------+---------+
| MainGearID | MainGearName           | MainGearType    | Spur     | Helical |
+------------+------------------------+-----------------+----------+---------+
|          1 | Main Drive             | Spur            | 112,280, |         |
|          2 | Secondary Drive        | Spur            | 144,248, |         |
|          3 | Backup Secondary Drive | Hypoid          |          | 18,     |
|          4 | AUX Drive              | Rack and pinion | 144,     |         |
+------------+------------------------+-----------------+----------+---------+

有人知道如何以这种方式创建视图吗?

解决方法:

您可以将GROUP_CONCAT与IF()结合使用:

CREATE VIEW v6 AS 
SELECT a.MainGearID, a.MainGearName, a.MainGearType, 
   GROUP_CONCAT(IF(b.OrbitalType='Spur',b.OrbitalValue,null)) AS Spur,
   GROUP_CONCAT(IF(b.OrbitalType='Helical',b.OrbitalValue,null)) AS Helical
 FROM gears a
 JOIN orbitinggears b on b.MainGearID=a.MainGearID
 GROUP BY a.MainGearID;

标签:multiple-tables,multiple-columns,sql-view,mysql
来源: https://codeday.me/bug/20191028/1949521.html