2015-12-02 45 views
0

我有問題,以下內容連接表:MySQL的:加入分組數據表 - 只有第一排連接

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 | 
+----+--------------+-------------+--------+-----------+---------+ 

我想所有的行,如果數據不能加入(價值CID_RingType),而不是簡單地返回NULL

感謝, 茲比涅克

+0

可能是因爲這個位:Number)AS'FromValue', min(r.Number – Strawberry

回答

1

我不認爲你需要在主查詢兩分鐘()函數,因爲你已經在子查詢中獲取最小值。

此外,它不是一個真正的好主意,做數學一列,可能是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子句有第一個表中所列第一。

+0

這是它,謝謝 – Zbynek