表的MySQL行号

时间:2013-04-04 23:14:15

标签: mysql sql

我正在尝试为我的桌子获取行号。 到目前为止,这是我的SQL提示符:

SELECT @i = @i + 1 AS Rank, x.Name, x.PartyName, x.ConstituencyName, x.Votes 
FROM (
    SELECT CONCAT(t1.Firstname, ' ', t1.Lastname) AS Name, t1.PartyName, t1.ConstituencyName, COALESCE(t2.Count, 0) AS Votes
        FROM (
            (SELECT db.user.PID, db.user.Firstname, db.user.Lastname, db.party.PartyName, db.constituency.ConstituencyName 
                FROM db.user
                LEFT JOIN db.party ON db.user.PartyId = db.party.PartyID 
                LEFT JOIN db.constituency ON db.user.CID = db.constituency.CID
                WHERE db.user.PartyId IS NOT NULL
                AND db.user.CID IS NOT NULL
            ) t1
            LEFT JOIN
            (SELECT db.user.Vote, COUNT(*) AS 'Count' 
                FROM db.user 
                GROUP BY db.user.Vote
            ) t2
        ON
            t1.PID = t2.Vote
        ORDER BY t2.Count DESC)
        ) x,
(SELECT @i:=1) r

所以这基本上是这样的,首先我创建一个表t1(从2个不同的表中获取信息)然后将它与表t2连接起来,这样我就能得到每个候选人的总票数。然后我将该表标记为'x'并将其与表'r'连接起来,该表应初始化行号(使用行号的在线教程)。但是,当我运行此SQL提示时,我得到以下内容:

Rank    Name    PartyName   ConstituencyName    Votes
0       Name1   Party1      Constituency1       700
0       Name2   Party1      Constituency1       550

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:3)

这是用户变量,您应该使用:=而不是=

SELECT @i := @i + 1 AS Rank,...