Sql server SQL Server,从在另一个表中使用id的表中选择随机项
考虑到简单的数据库结构:Sql server SQL Server,从在另一个表中使用id的表中选择随机项,sql-server,join,random,Sql Server,Join,Random,考虑到简单的数据库结构: Account - Id (Primary Key) Root - Id (Primary Key) - AccountId (FK to Account) - Private (bit) RootItem - Id (Primary Key) - AccountId (FK to Account) - RootId (FK to Root) 有人知道如何编写SQL语句来执行以下操作吗 考虑到我只知道某人的Account.
Account
- Id (Primary Key)
Root
- Id (Primary Key)
- AccountId (FK to Account)
- Private (bit)
RootItem
- Id (Primary Key)
- AccountId (FK to Account)
- RootId (FK to Root)
有人知道如何编写SQL语句来执行以下操作吗
考虑到我只知道某人的Account.Id为int,让我们假设@AccountId=1。
选择一个随机根记录,该根记录具有无附加的根项目记录,该记录的AccountId为=@AccountId,其中Root.Private为0
这是针对SQL Server的,任何帮助都将不胜感激,我不太擅长SQL连接
select top 1 *
from
Root r
left join
RootItem ri
on
r.Id = ri.RootID and
ri.AccountId = @AccountID
where
r.Private = 0 and
ri.Id is null
order by
newid()
为了消除具有与帐户ID匹配的RootItems的根,我们执行上面的左连接,但是在where子句中,我们确保(ri.ID为null)没有实际发生匹配。要随机选择一行,我们按newid()排序,这将为每一行生成一个新的GUID,然后只选择前1行
如果我们需要一个更强大的随机性源,或者一些好的统计特性,我们可能必须考虑在CLR中工作。非常好,非常适合
NEWID()
+1.