MySQL:将分组数据连接到表 - 仅加入第一行

时间:2015-12-02 16:57:52

标签: mysql join group-by

我在使用以下内容加入表时遇到问题:

RingOrderItem

+----+-------------+--------+
| ID | ID_RingType | Amount |
+----+-------------+--------+
|  1 | A           |    100 |
|  2 | B           |     50 |
|  3 | A           |    500 |
|  4 | C           |    100 |
+----+-------------+--------+

分组表Rings - SELECT min(Rings.Number) AS Number, ID_RingType FROM Rings GROUP BY ID_RingType声明的结果:

+--------+-------------+
| Number | ID_RingType |
+--------+-------------+
|      1 | A           |
|      1 | B           |
+--------+-------------+

我想从RingOrderItem检索所有记录,并将分组表Rings中的号码连接到它们,我使用了这个查询:

SELECT
    roi.ID,
    roi.ID_RingOrder,
    roi.ID_RingType,
    roi.Amount,
    min(r.Number) AS `FromValue`,
    min(r.Number) + roi.Amount - 1 AS `ToValue`
FROM
    RingOrderItem AS roi
LEFT JOIN
    (SELECT min(Rings.Number) AS Number, ID_RingType FROM Rings 
        GROUP BY ID_RingType) 
    AS r ON r.ID_RingType = roi.ID_RingType;

出于某种原因,我只从RingOrderItem表中获得第一行:

+----+--------------+-------------+--------+-----------+---------+
| ID | ID_RingOrder | ID_RingType | Amount | FromValue | ToValue |
+----+--------------+-------------+--------+-----------+---------+
|  1 |            1 | A           |    100 |         1 |     100 |
+----+--------------+-------------+--------+-----------+---------+

我想要所有行,如果数据无法加入(C中的值ID_RingType),则只返回NULL

谢谢, 兹比涅克

1 个答案:

答案 0 :(得分:1)

我认为您不需要主查询上的两个min()函数,因为您已经在子查询中获取了最小值。

此外,对可能为NULL的列进行数学运算并不是一个好主意

试试这个:

SELECT
    roi.ID,
    roi.ID_RingOrder,
    roi.ID_RingType,
    roi.Amount,
    r.Number AS FromValue,
    COALESCE(r.Number, 0) + roi.Amount - 1 AS ToValue
FROM
    RingOrderItem AS roi
LEFT JOIN
    (
        SELECT 
            MIN(Rings.Number) AS Number, 
            ID_RingType 
        FROM 
            Rings 
        GROUP BY 
            ID_RingType
    ) AS r ON roi.ID_RingType = r.ID_RingType;

此外,切换左连接ON子句以使第一个表首先列出。