SQL 服务器 & ASP.NET & C# : select 前 20 张图片中的 5 张随机图片

SQL Server & ASP.NET & C# : select 5 random images from top 20 images

我有点SQL问题。

我想要 select 最高 ID 的 20 行中的随机 5 行。我怎么做?目前我的 SqlDataSource 看起来像这样:

<asp:SqlDataSource ID="SqlDataSource25" runat="server" 
     ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>"
     ProviderName="<%$ ConnectionStrings:DatabaseConnectionString1.ProviderName %>"
     SelectCommand="SELECT TOP 5 * FROM [billeder] ORDER BY newid()">  
</asp:SqlDataSource>

这意味着我当然只是从整个 table 中随机得到 5 个。

我更愿意通过 SqlDataSource 来完成,正如您在此处看到的那样,但如果只能通过代码隐藏来实现,那也很好。任何提示将不胜感激。

您需要使用子查询按 ID 获取前 20 个,然后从这 20 个中您可以 select 前 5 个:

SELECT TOP 5 * 
FROM (  SELECT  TOP 20 * 
        FROM [billeder] 
        ORDER BY ID DESC
    ) AS t 
ORDER BY NEWID();
select  * from [billeder] where [yourPk] in 
(select top 5 percent [yourPk] from [billeder] order by newid())

你的主键是主键