2016-07-24 43 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不起作用,但是您沒有要求它... –