下面的 mySql 查询有问题
SELECT name, hospitalID, currentAvgRating, rank
FROM ( SELECT name,hospitalID,currentAvgRating,city,
@curRank := @curRank + 1 AS rank
FROM hospitals h, ( SELECT @curRank := 0) r
ORDER BY currentAvgRating DESC
) toplist
WHERE toplist.hospitalID = @hospitalID
and city = @city
我正在使用此查询来查找特定项目的排名,它工作正常。但是在程序中运行时,我得到必须定义参数 '@curRank' 的 fatal error 。但那是 mysql 语法,那么我怎样才能得到它的参数呢?
更新
string str = "SELECT name, hospitalID, currentAvgRating, rank FROM (SELECT name,hospitalID,currentAvgRating,city,@curRank := @curRank + 1 AS rank FROM hospitals h, (SELECT @curRank := 0) r ORDER BY currentAvgRating DESC) toplist WHERE toplist.hospitalID = @hospitalID and city = @city";
con.Open();
MySqlCommand cmd = new MySqlCommand(str, con);
cmd.Parameters.AddWithValue("@hospitalID", generalID.Text);
cmd.Parameters.AddWithValue("@city", cityName.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
最佳答案
您可以获得没有排名的特定医院/城市对的排名。这是您的查询的近似值:
select count(*) + 1 as ranking
from hospitals h cross join
(select h.currentAvgRating
from hospitals h
where h.hospitalID = @hospitalID and h.city = @city
) hh
where h.currentAvgRating > hh.currentAvgRating;
与您的代码不同,这会为所有医院提供相同的评级和相同的排名。
如果不想改代码,可以引用这个answer .其实,我会引用相关部分:
I have to add
;Allow User Variables=True
to the connection string
关于c# - 简化非参数化 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38674679/