1

我想从多个表中选择数据,如下所示。我希望每组“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 
4

1 回答 1

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每组唯一)。

于 2012-06-25T03:28:52.373 回答