3

我有一张桌子,看起来像:

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 行?

4

2 回答 2

2

您可以将排名从 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

注意:我使用了一个旧答案并改进了随机化。我得到帮助的旧答案是: 为每个类别选择 N 条记录并按 X 排序

于 2012-09-01T20:10:24.827 回答
0

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
)
于 2012-09-01T19:47:39.760 回答