开发者

Sql query for filtering data with WHERE clause on same column

开发者 https://www.devze.com 2023-03-23 09:43 出处:网络
I have to tables: Table A id | title 1| toto 2| tata 3| titi Table B id | title_id | tag_id 1|1|6 2|1|16 3|1|26

I have to tables:

Table A
id | title
1  | toto
2  | tata
3  | titi 


Table B
id | title_id | tag_id
1  |    1     |   6
2  |    1     |   16
3  |    1     |   26
4  |    2     |   6
5  |    2     |   7
6  |    2     |   16
7  |    3     |   2
8  |    3     |   1
9  |    3     |   16

(Sorry for the bad table display)

In my application I have a tag listview with checkboxes, and when the user clicks a checkbox, I want to filter the titles with the clicked checkboxes: (E.g: if user clicks tag 16, I should have title 1, 2 and 3 displayed. But if user clicks tag with id 26 AND tag with id 16, as result I should have only title with id 1)

I thought to a query like that:

SELECT DISTINCT A.titl开发者_运维知识库e , A.id FROM A INNER JOIN B ON B.title_id = A.id WHERE B.tag_id = 26 AND B.tag_id = 16;

but obviously the last part of the query (two AND clause on a same column) is wrong, and I do not find a query which will give me this result.

I tried this :

SELECT DISTINCT A.title , A.id FROM A INNER JOIN B ON B.title_id = A.id WHERE B.tag_id IN ( '26', '16');

but the IN clause is like a OR clause, and as result, I get all the rows for value 26 plus all the rows for value 16 (title 1, 2 and 3) and not ONLY title 1. I absolutely need to do this with and sql query because I'm using a SimpleCursorAdapter in order retrieve the datas and to fill an other listview.

I searched for a while, but I didn't find any relevant solution. (Or maybe I typed the wrong words...)

Do you have solution for me please?

PS: I hope I've been clear. Sorry for my bad english.


Use subqueries:

SELECT DISTINCT A.title, A.id FROM A WHERE
    A.id IN (SELECT DISTINCT B.title_id FROM B WHERE B.tag_id='16')
    AND A.id IN (SELECT DISTINCT B.title_id FROM B WHERE B.tag_id='26')
0

精彩评论

暂无评论...
验证码 换一张
取 消