请原谅我的问题标题,我不确定我应该说什么,我有这两个表如下。
products orders
+------+----------+ +--------+------+-------+
| id | name | | id | qty | pid |
+------+----------+ +--------+------+-------+
| 1 | mouse | | 10001 | 20 | 1 |
| 2 | keyboard | | 10002 | 15 | 3 |
| 3 | headset | | 10004 | 5 | 3 |
+------+----------+ | 10005 | 12 | 2 |
| 10006 | 18 | 1 |
+--------+------+-------+
这是我正在使用的 LEFT JOIN 查询和输出
SELECT p.id AS No, p.name AS ProductName, o.qty AS Quantity
FROM products AS p
LEFT JOIN orders AS o ON p.id = o.pid
+------+-------------+----------+
| No | ProductName | Quantity |
+------+-------------+----------+
| 1 | mouse | 20 |
| 1 | mouse | 18 |
| 2 | keyboard | 12 |
| 3 | headset | 15 |
| 3 | headset | 5 |
+------+-------------+----------+
我想要实现的是如下输出:
+------+-------------+----------+
| No | ProductName | Quantity |
+------+-------------+----------+
| 1 | mouse | 20 |
| | | 18 |
| 2 | keyboard | 12 |
| 3 | headset | 15 |
| | | 5 |
+------+-------------+----------+
我的问题是可以这样做吗?任何回复和建议都非常感谢。谢谢。
P/S:我也尝试过使用 GROUP_CONCAT(qty SEPARATOR ",") 但它会在一行中返回结果,因为将来我可能会在 Orders 表中添加更多额外的列,并且很难阅读。