Sqlite - 同一个 Table 上的多个 INNER JOIN 与 Limit

Sqlite - Multiple INNER JOIN on same Table with Limit

在我的 Android 应用程序中,我有一个带有 6 个主题 ID 的问题 Table 的 Sqlite 数据库。现在我想获得每个主题的一定数量的问题。这意味着:15 个主题 ID 为 1 的问题、5 个主题 ID 为 2 的问题、7 个主题 ID 为 3 和 4 的问题以及 3 个主题 ID 为 5 和 6 的问题。

我想我需要一个 multipe inner join 和 limit 函数,但我不太了解如何构建这样的查询。

你有什么想法吗?

一个简单的方法是使用union alllimit:

(select q.* from questions q where q.topicid = 1 order by random() limit 15) union all
(select q.* from questions q where q.topicid = 2 order by random() limit 5) union all
(select q.* from questions q where q.topicid in (3, 4) order by random() limit 7) union all
(select q.* from questions q where q.topicid in (5, 6) order by random() limit 3) ;

我没有意识到 SQLite 似乎有子查询和 union all 的问题。无论如何,这个版本似乎 work:

with q1 as
    (select q.* from questions q where q.topicid = 1 order by random() limit 15),
     q2 as
    (select q.* from questions q where q.topicid = 2 order by random() limit 5),
    q34 as 
    (select q.* from questions q where q.topicid in (3, 4) order by random() limit 7),
    q56 as
    (select q.* from questions q where q.topicid in (5, 6) order by random() limit 3)
select * from q1 union all
select * from q2 union all
select * from q34 union all
select * from q56;

要连接来自多个查询的行,请使用 compound query

复合查询中的查询不允许使用 LIMIT,因此必须将其移至子查询中:

SELECT * FROM (SELECT * FROM Questions
               WHERE TopicID = 1
               ORDER BY random() LIMIT 15)
UNION ALL
SELECT * FROM (SELECT * FROM Questions
               WHERE TopicID = 2
               ORDER BY random() LIMIT  5)
UNION ALL
...

试试这个用于组合来自两个或多个表的行的示例http://www.w3schools.com/sql/sql_join.asp