MySQL SELECT按组递增

时间:2012-06-25 02:23:16

标签: mysql select

我想从多个表中选择数据,如下所示。我希望每组'dID'都有'gID'自动增量。我正在查询的多个表没有自动增量值。因此必须动态创建gID字段。

dID     gID     bID     data
===     ===     ===     ====
400     1       20     data1
400     2       21     data2
401     1       28     data3
402     1       52     data4
402     2       74     data5
402     3       75     data6
402     4       89     data7

我无法弄清楚如何实现这一目标。

我尝试过这样做,但它似乎没有起作用:

SELECT t1.dID, @i:=@i+1 AS gID, t2.bID, t2.data
FROM table1 t1, table2 t2, (SELECT @i:=0) m
WHERE t1.mID = t2.mID
ORDER BY t1.dID 

1 个答案:

答案 0 :(得分:2)

不需要“@”变量......试试这个:

SELECT 
    a.dID, 
    COUNT(*) AS gID, 
    b.bID, 
    b.data
FROM 
    table1 a
INNER JOIN 
    table2 b ON a.mID = b.mID
INNER JOIN
    (
        SELECT a.dID, b.bID
        FROM table1 a
        INNER JOIN table2 b ON a.mID = b.mID
    ) c ON a.dID = c.dID AND b.bID >= c.bID
GROUP BY 
    a.dID,
    b.bID
ORDER BY
    a.dID,
    gID

此解决方案还允许bID具有重复值(每个dID组唯一)。