在我的Android应用程序中,我有一个带有6个主题ID的问题表的Sqlite数据库。现在我想得到每个主题的一定数量的问题。这意味着:15个主题ID为1的问题,5个主题为ID,7个主题为ID 3,4个为3个主题为ID 5和6。
我认为我需要一个multipe内连接和限制功能,但我不太了解构建这样的查询。
你有什么想法吗?
答案 0 :(得分:2)
一种简单的方法是使用union all
和limit
:
(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;
答案 1 :(得分:0)
要连接多个查询中的行,请使用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
...
答案 2 :(得分:0)
尝试此示例用于组合来自两个或多个表http://www.w3schools.com/sql/sql_join.asp
的行