2

我有一个使用 MySQL 会话变量的查询(注意 @rank 变量)

SELECT Rank, UserId, CurrentVDOT
FROM
    (
        SELECT @rank := @rank + 1 AS Rank, UserId, MaxVDOT AS CurrentVDOT
        FROM
            (
                SELECT UserId, MAX(VDOT) AS MaxVDOT
                FROM
                    (
                        SELECT U.UserId, U.VDOT
                        FROM
                            (
                                SELECT UserId, MAX(Created) AS Created
                                FROM UserVDOT
                                GROUP BY UserId
                            ) G
                        INNER JOIN UserVDOT U
                        ON U.UserId = G.UserId
                            AND U.Created = G.Created
                    ) M
                GROUP BY UserId
                ORDER BY MaxVDOT DESC
            ) R, (SELECT @rank := 0) foo
    ) F
WHERE F.UserId = @UserId;

如果我尝试针对 C# MySQL 连接器执行此操作,它会尝试告诉我需要将 @rank 声明为输入参数变量。

有没有办法解决?

谢谢。

4

2 回答 2

9

你好艾莉森!

我最近遇到了同样的问题,但我发现默认情况下,SQL 连接禁用在查询中使用变量。要解决此问题,您可以启用连接字符串,如下所示:

连接字符串:

server=192.168.0.0;password=root;User Id=root;Persist Security Info=True;database=my_db;Allow User Variables=True

您必须输入连接参数Allow User Variables=True才能使其工作。

我希望我有所帮助。

海吾高木

于 2013-06-10T18:26:45.583 回答
2

如果您不想通过设置连接字符串来进行全局更改,还有另一种方法。

这可以通过用单引号将名称括起来来完成,'如下所示。

SELECT Rank, UserId, CurrentVDOT
FROM
    (
        SELECT @'rank' := @'rank' + 1 AS Rank, UserId, MaxVDOT AS CurrentVDOT
        FROM
            (
                SELECT UserId, MAX(VDOT) AS MaxVDOT
                FROM
                    (
                        SELECT U.UserId, U.VDOT
                        FROM
                            (
                                SELECT UserId, MAX(Created) AS Created
                                FROM UserVDOT
                                GROUP BY UserId
                            ) G
                        INNER JOIN UserVDOT U
                        ON U.UserId = G.UserId
                            AND U.Created = G.Created
                    ) M
                GROUP BY UserId
                ORDER BY MaxVDOT DESC
            ) R, (SELECT @'rank' := 0) foo
    ) F
WHERE F.UserId = @UserId;

它现在将被视为会话变量。

于 2017-08-10T05:33:11.190 回答