随机记录,但每个类别中的最大记录

时间:2012-04-23 07:57:00

标签: mysql

我想获得3张随机邮票,但每张邮票来自不同国家。此查询返回随机戳记,但可以来自同一个国家/地区。当我添加GROUP BY country_id时,我会得到3个不同国家的邮票,但只有每个国家的第一张邮票。

SELECT `stamps`.`stamp_id`, `countries`.`country_name_cs` FROM `stamps`
LEFT JOIN `countries` ON countries.country_id = stamps.country_id
WHERE (stamps.stamp_enabled = 1) ORDER BY rand() ASC LIMIT 3

有什么想法吗?

查询个人资料(#Ezequiel Muns解决方案)

starting              0.000232
Opening tables        0.000047
System lock           0.000013
Table lock            0.000635
optimizing            0.000036
statistics            0.000022
preparing             0.000023
Creating tmp table    0.000293
executing             0.000004
Copying to tmp table  0.060066
Sorting result        0.013835
Sending data          0.089164
removing tmp table    0.000632
Sending data          0.000026
init                  0.000048
optimizing            0.000014
statistics            0.000061
preparing             0.000028
Creating tmp table    0.000326
executing             0.000004
Copying to tmp table  0.353176
Sorting result        0.000158
Sending data          0.000038
end                   0.000005
removing tmp table    0.000018
end                   0.000006
query end             0.000004
freeing items         0.000575
removing tmp table    0.002363
closing tables        0.000023
logging slow query    0.000004
cleaning up           0.000009

id      select_type       table      type       possible_keys       key         key_len     ref           rows      Extra
1       PRIMARY       <derived2>     ALL        NULL                NULL        NULL        NULL          12679     Using temporary; Using filesort
1       PRIMARY       c              eq_ref     PRIMARY             PRIMARY     4           s.country_id  1      
2       DERIVED       stamps         ALL        NULL                NULL        NULL        NULL          12679     Using where; Using temporary; Using filesort

2 个答案:

答案 0 :(得分:2)

SELECT
    c.country_id,
    c.country_name_cs,
    s.stamp_id
FROM country c
    JOIN (
        SELECT * 
        FROM stamps
        WHERE stamp_enabled = 1
        ORDER BY RAND()
    ) AS s ON c.country_id = s.country_id
GROUP BY c.country_id, c.country_name_cs
ORDER BY RAND()
LIMIT 3;

您首先将所有国家/地区加入各自的邮票,但是按随机顺序排列,然后将该列表修改为每个国家/地区的第一个(随机选择)标记。外部查询的ORDER BY使您选择的国家/地区随机化,然后LIMIT仅返回3.

像大卫Z说的那样,效率低下。

答案 1 :(得分:1)

您可以尝试以下查询,首先选择3个随机国家/地区,使用混合戳记表格执行联接,然后按国家/地区分组。效率不高,但适用于较小的数据集。

 SELECT
    mixed_stamp.stamp_id,
    random.country_name_cs
 FROM
    (SELECT * FROM stamps ORDER BY RAND()) AS mixed_stamp
 LEFT JOIN (SELECT country_id FROM countries ORDER BY RAND() LIMIT 3) random ON (random.country_id = mixed_stamp.country_id)
 GROUP BY random.country_id