【问题标题】:Selecting two different random entries for each category with mySQL使用 mySQL 为每个类别选择两个不同的随机条目
【发布时间】:2012-09-01 17:31:51
【问题描述】:

我有一个看起来像这样的表:

table: Q
---------------------------
|question| scope |  type  |
---------------------------
|  this  |   A   |   1    |
|  that  |   A   |   1    |
|  them  |   A   |   1    |
---------------------------
|  this  |   A   |   2    |
|  that  |   A   |   2    |
|  them  |   A   |   2    |
---------------------------
|  this  |   B   |   1    |
|  that  |   B   |   1    |
|  them  |   B   |   1    |
---------------------------

我需要给定一个范围,我需要从每种类型中提取两个条目。如果范围是 A,可能的解决方案是:

---------------------------
|  this  |   A   |   1    |
|  them  |   A   |   1    |
---------------------------
|  that  |   A   |   2    |
|  this  |   A   |   2    |
---------------------------

我目前正在使用以下 SQL 语句:

SELECT tmp.question, tmp.type, tmp.scope
FROM Q
LEFT JOIN (
SELECT * FROM Q ORDER BY RAND( )
)tmp ON ( Q.type = tmp.type AND tmp.scope = 'A' ) 
GROUP BY tmp.type
ORDER BY Q.type

但是,这仅返回每种类型的一个条目,并且由于某种原因返回 NULL 行。
因此,我的问题是如何优化语句以返回两行并消除 NULL 行?

【问题讨论】:

  • 我会请您编辑您的问题。我认为您要求两个不同随机选择、来自每个不同type 的条目。对吗?

标签: mysql group-by left-join


【解决方案1】:

您可以将排名从 2 更改为您想为每个类别获得的任何排名。

http://www.sqlfiddle.com/#!2/f3946/86

试试这个:

  SELECT x.question,
       x.scope,
       x.type
  FROM (

    SELECT bp.question, bp.scope, bp.type, 
    CASE WHEN bp.type = @type 
         THEN @rownum := @rownum + 1
         ELSE @rownum := 1
         END AS rank,
    @type := bp.type
FROM (select * from Q order by rand()) bp
JOIN (SELECT @rownum := 0, @type := NULL) r
WHERE bp.scope = 'A'
ORDER BY type
    ) x
 WHERE x.rank <= 2
order by x.type

注意:我使用了旧答案并改进了随机化。 我得到帮助的旧答案是: Select N records for each category and order by X

【讨论】:

  • 哇,这是一个复杂的陈述,但它确实有用!非常感谢!
【解决方案2】:

SqlFiddle

(
  SELECT question, scope, type FROM Q
  WHERE  scope = 'A' AND type = 1
  ORDER BY RAND() LIMIT 2
)
UNION
(
  SELECT question, scope, type FROM Q
  WHERE  scope = 'A' AND type = 2
  ORDER BY RAND() LIMIT 2
)

【讨论】:

  • @AndreasJarbol 我认为是这样。我显然误解了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
相关资源
最近更新 更多