我想从基于费率字段的数据库中按百分比获取数据,我也想随机显示数据 所以我试过这个
string sql = "(SELECT TOP 100 PERCENT * FROM tbl_adv WHERE Stars = 7 ORDER BY Rnd(-(1000*adID)*Time())) UNION (SELECT TOP 84 PERCENT * FROM tbl_adv WHERE Stars = 6 ORDER BY Rnd(-(1000*adID)*Time())) UNION (SELECT TOP 72 PERCENT * FROM tbl_adv WHERE Stars = 5 ORDER BY Rnd(-(1000*adID)*Time()))";
它显示正确的数据,但不是随机的, 有什么建议吗?
我也提供了一个测试用样本,您可以从下面的链接下载 http://www.4shared.com/zip/qMSYRglGce/testorderby.html
答案 0 :(得分:3)
在 UNION 查询中, ORDER BY 应该应用于 UNION 返回的整个集合 因此,您可以从三个子选择中构建一组记录,然后将顺序应用于结果集。
string sql = @"SELECT * FROM
(
SELECT TOP 100 PERCENT * FROM tbl_adv WHERE Stars = 7
UNION
SELECT TOP 84 PERCENT * FROM tbl_adv WHERE Stars = 6
UNION
SELECT TOP 72 PERCENT * FROM tbl_adv WHERE Stars = 5
)
ORDER BY Rnd(-(1000*adID)*Time())";