我在下面的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'的致命错误。但那是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();
答案 0 :(得分:1)
您可以获得没有排名的特定医院/城市对的排名。以下是您的查询的近似值:
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。实际上,我引用了相关部分:
我必须添加
;Allow User Variables=True
连接字符串
答案 1 :(得分:0)
你的SQL是正确的我认为有C#命令参数和mySQL参数
的混淆尝试像这样修改SQL代码
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
你喜欢这个
string str = <Example Above>;
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();
只需更改C#命令参数?而不是使用@