我有一个项目,我正在创建一个由数据库驱动的游戏。
数据库输入的数据如下:
(身份证,姓名)|| (1,PhotoID),(1,PhotoID),(1,PhotoID),(2,PhotoID),(2,PhotoID)等。有数以千计的参赛作品。
这是我当前的SQL语句:
$sql = "SELECT TOP 8 * FROM Image WHERE Hidden = '0' ORDER BY NEWID()";
但是这也会产生匹配ID的结果,我需要让每个结果都有一个唯一的ID(我需要每个组得到一个结果)。
如何更改查询以从每个组中获取一个结果?
谢谢!
答案 0 :(得分:4)
由于ORDER BY NEWID()
无论如何都会导致表扫描,你可以使用row_number()来隔离第一组:
; with randomizer as (
select id,
name,
row_number() over (partition by id
order by newid()) rn
from Image
where hidden = 0
)
select top 8
id,
name
from randomizer
where rn = 1
-- Added by mellamokb's suggestion to allow groups to be randomized
order by newid()
Sql Fiddle playground感谢mellamokb。
答案 1 :(得分:2)
看起来这可行,但我无法保证性能:
SELECT TOP 8 ID,
(select top 1 name from image i2
where i2.id = i1.id order by newid())
FROM Image i1
WHERE hidden = '0'
group by ID
ORDER BY NEWID();
答案 2 :(得分:2)
如果您在ID
列上有索引并希望利用索引并避免全表扫描,请先对关键值进行随机化:
WITH IDs AS
(
SELECT DISTINCT ID
FROM Image
WHERE Hidden = '0'
),
SequencedIDs AS
(
SELECT ID, ROW_NUMBER() OVER (ORDER BY NEWID()) AS Seq
FROM IDs
),
ImageGroups AS
(
SELECT i.*, ROW_NUMBER() OVER (PARTITION BY i.ID ORDER BY NEWID()) Seq
FROM SequencedIDs s
INNER JOIN Image i
ON i.ID = s.ID
WHERE s.Seq < 8
AND i.Hidden = '0'
)
SELECT *
FROM ImageGroups
WHERE Seq = 1
这应该大大降低了表扫描方法的成本,虽然我没有足够大的模式可以测试 - 所以尝试在SSMS中运行一些统计信息并确保ID
实际上已为其编制索引这是有效的。
答案 3 :(得分:1)
select * from (select * from photos order by rand()) as _SUB group by _SUB.id;
答案 4 :(得分:0)
select ID, Name from (select ID, Name, row_number() over
(partition by ID, Name order by ID) as ranker from Image where Hidden = 0 ) Z where ranker = 1
order by newID()