2016-07-24 65 views
0

在我的Android应用程序中,我有一个包含6个主题ID的Sqlite数据库。现在我想要获得每个主题的一定数量的问题。这意味着:15个问题的主题ID 1,5,主题ID 2,7的主题ID 3和4和3的主题ID 5和6.Sqlite - 同一个表上的多个INNER JOIN限制

我想我需要一个multipe内部连接和限制函数,但我不太了解如何构建这样的查询。

你有什么想法吗?

回答

2

一个简单的方法是使用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; 
+0

由于结合,但是当我使用你的查询时,我得到一个SQL语法错误。 –

+0

错误是什么? –

+0

仅当允许(在FROM子句中)表名或标量子查询时才允许子查询。 UNION想要一个'真实'的查询,所以你必须围绕它来包装另一个查询。 –

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 
... 
+0

当我使用你的查询时,我也得到一个SQL语法错误。 –

+0

如果没有单独的间接寻址,最后的ORDER BY不起作用,但是您没有要求它... –