MySQL - 为每个类别选择单个条目

时间:2014-02-17 00:28:07

标签: mysql sql

道歉。我把下面的内容编辑成了2个表格,我只是有些困惑。


我的表格与下面的表格非常相似,我希望显示所有table2-class 1,但每个table1-category只有1个随机项目

样本项目表1

+---------+---------------+---------------+
|   ID    |   Item Name   |    Category   |
+---------+---------------+---------------+
|   01    |    Item A     |     Cat 1     |
|   02    |    Item B     |     Cat 1     |
|   03    |    Item C     |     Cat 2     |
|   04    |    Item D     |     Cat 2     |
|   05    |    Item E     |     Cat 3     |
|   06    |    Item F     |     Cat 3     |
+---------+---------------+---------------+

示例项目表2

+---------------+---------------+
|    Category   |     Class     |
+---------------+---------------+
|     Cat 1     |       1       |
|     Cat 2     |       1       |
|     Cat 3     |       2       |
+---------------+---------------+

我想显示所有table2-class 1,但每个table1-category

只显示1个随机项目

期望的结果

+---------+---------------+---------------+
|   02    |    Item B     |     Cat 1     |
|   03    |    Item C     |     Cat 2     |
+---------+---------------+---------------+

(这是在我的PHP脚本中)

提前致谢

4 个答案:

答案 0 :(得分:3)

你可以做这样的事情

SELECT t.id, itemname, category
  FROM
(
  SELECT 
  (
    SELECT id
      FROM table1
     WHERE category = t.category
     ORDER BY RAND()
     LIMIT 1
  ) id
    FROM table1 t
   GROUP BY category
) q JOIN table1 t
    ON q.id = t.id

注意:使用RAND()非常昂贵

输出:

| ID | ITEMNAME | CATEGORY |
|----|----------|----------|
|  1 |   Item A |    Cat 1 |
|  3 |   Item C |    Cat 2 |
|  6 |   Item F |    Cat 3 |

这是 SQLFiddle 演示

答案 1 :(得分:0)

尝试这样的事情:

SELECT id, itemname, category FROM (
  SELECT id, itemname, category FROM sample_table 
  ORDER BY RAND()
) AS tmp
GROUP BY category

请注意,此查询在MySQL中完全有效 http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html

答案 2 :(得分:0)

最安全的方法是使用相关子查询。获取item_id

select category,
       (select item_id from sample s where s2.category = s.category order by rand() limit 1) as item_id
from sample s
group by category;

要获取其余的项目信息,请将其重新加入:

select s.*
from (select category,
             (select item_id from sample s where s2.category = s.category order by rand() limit 1) as item_id
      from sample s
      group by category
     ) c join
     sample s
     on s.item_id = c.item_id;

答案 3 :(得分:0)

在上面编辑的场景之前,我使用了以下查询,它工作正常,只是它没有随机化每个类别的条目:

SELECT * FROM Table1,Table2
WHERE Table2.Class = '1'
 AND Table1.Category = Table2.Category
GROUP BY Table1.Category ORDER BY RAND()