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

How to create View in MySQL to combine rows from second table as CSV colmuns in first

我需要在 MySQL 中创建 VIEW,它可以组合两个 table,这样对于第一行 table 的每一行,必须添加第二行 [=23] 的列=] 但由于行数据必须格式化为多个字段,每一行都有多个 CSV。

我最初的方法是使用 MySQL VIEW,但我无法找到在视图 table 中将来自第二个 table 的多行数据显示为 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_CONCATIF() 一起使用:

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;