使用NEWID()从表中检索随机行

Git*_*itz 3 sql sql-server

我有一个SQL查询,我正在使用distinct语句

   CREATE proc SProc_SelectPhotographersByLocation         
@locationID varchar(500)          
as            
begin          


DECLARE @TEST varchar(1000)          
DECLARE @SQLQuery AS NVARCHAR(1000)          

SET @TEST = @locationID          

SET @SQLQuery = 'select distinct ContributerSubCategoryMapping.ContributorID,  PhotographerContributors_tbl.*  from ContributerSubCategoryMapping               
  left outer join PhotographerContributors_tbl on PhotographerContributors_tbl.ContributorId=ContributerSubCategoryMapping.ContributorID              
  left outer join tbl_City on tbl_City.CityID=PhotographerContributors_tbl.Location              
  where         
  PhotographerContributors_tbl.Location IN('+ @locationID +') and PhotographerContributors_tbl.IsActive=''1'' order by Newid()'          
EXECUTE(@SQLQuery)          

end
Run Code Online (Sandbox Code Playgroud)

当我NEWID()在该查询上使用时,我收到查询错误.错误是

如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中.

请帮我解决这个问题

Gor*_*off 5

group by而不是distinct.一种方法是明确列出列:

select csm.ContributorID, pc.col1, pc.col2, . . .
from ContributerSubCategoryMapping csm left outer join
     PhotographerContributors_tbl pc
     on pc.ContributorId = csm.ContributorID left outer join
     tbl_City c
     on c.CityID = pc.Location              
where pc.Location IN ('+ @locationID +') and pc.IsActive=''1''
group by csm.ConstributorId, pc.col1, pc.col2, . . .
order by Newid();
Run Code Online (Sandbox Code Playgroud)

但是,我不理解查询.这些表格ContributerSubCategoryMappingtbl_City似乎并没有被使用.那么为什么不这样做呢?

select pc.*
from PhotographerContributors_tbl pc
where pc.Location IN ('+ @locationID +') and pc.IsActive=''1''
order by Newid();
Run Code Online (Sandbox Code Playgroud)

  • 是的,总结了我的所有想法,为什么在没有使用时可以使用2个连接...也可以添加到*"一种方法是明确列出列"* - [无论如何应该这样做](http:// sqlblog .COM /博客/ aaron_bertrand /存档/ 2009/10/10 /坏习惯,对开球使用选-省略最柱list.aspx) (2认同)