2016-07-24 24 views
0

私のAndroidアプリケーションでは、質問テーブルが6つのトピックIDを持つSqliteデータベースを持っています。今私はすべてのトピックの特定の数の質問を取得したい。つまり、トピックID 1の15の質問、トピックID 2の5、トピックID 3の4、トピックID 5と6の3の質問を意味します。Sqlite - 複数のINNER JOINと同じテーブルに制限

私はマルチプルの内部結合が必要です私はこのようなクエリを構築することはあまり知られていません。

ご意見はありますか?

答えて

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は別の間接指定なしでは機能しませんが、あなたはそれを求めませんでした... –

関連する問題