我在使用以下内容加入表时遇到问题:
表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
。
谢谢, 兹比涅克
答案 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子句以使第一个表首先列出。