我有一张桌子,看起来像:
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 行?