0

请原谅我的问题标题,我不确定我应该说什么,我有这两个表如下。

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 表中添加更多额外的列,并且很难阅读。

4

2 回答 2

2

当然,这是可能的——而且不需要使用变量:

SELECT    IF(c.min_oid IS NOT NULL, a.id,   NULL) AS No,
          IF(c.min_oid IS NOT NULL, a.name, NULL) AS ProductName,
          b.qty AS Quantity
FROM      products a
JOIN      orders b ON a.id = b.pid
LEFT JOIN (
          SELECT   MIN(id) AS min_oid
          FROM     orders
          GROUP BY pid
          ) c ON b.id = c.min_oid
ORDER BY  a.id,
          b.id

基本上它所做的是如果该行不是特定产品的最小订单ID,则显示空白(NULL),否则显示信息。


SQLFiddle 演示

于 2012-08-05T07:43:05.910 回答
1

在这种情况下,您可以使用 MySQL 变量。我将之前的产品 id 存储在变量@prev中,只有当它发生变化时,我们才会输出产品名称。

http://www.sqlfiddle.com/#!2/d5fd6/9

SET @prev := NULL;

SELECT
  IF( @prev = p.id, NULL, p.id) AS No,
  IF( @prev = p.id, NULL, p.name) AS ProductName,
  o.qty AS Quantity
 ,@prev := p.id

FROM products AS p

LEFT JOIN orders AS o
       ON p.id = o.pid
于 2012-08-05T07:49:03.583 回答