Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a subset query in sql?

Tags:

sql

I have two tables as follows:

CREATE List (
    id   INTEGER,
    type INTEGER REFERENCES Types(id),
    data TEXT,
    PRIMARY_KEY(id, type)
);

CREATE Types (
    id   INTEGER PRIMARY KEY,
    name TEXT
);

Now I want to create a query that determines all ids of List which has given type strings.

For example,

List:
1    0    "Some text"
1    1    "Moar text"
2    0    "Foo"
3    1    "Bar"
3    2    "BarBaz"
4    0    "Baz"
4    1    "FooBar"
4    2    "FooBarBaz"

Types:
0    "Key1"
1    "Key2"
2    "Key3"

Given the input "Key1", "Key2", the query should return 1, 4.

Given the input "Key2", "Key3", the query should return 3, 4.

Given the input "Key2", the query should return 1, 3, 4.

Thanks!

like image 792
chacham15 Avatar asked Feb 20 '23 15:02

chacham15


1 Answers

select distinct l.id 
from list l
inner join types t on t.id = l.type
where t.name in ('key1', 'key2')
group by l.id
having count(distinct t.id) = 2

You have to adjust the having clause to the number of keys you are putting in your where clause. Example for just one key:

select distinct l.id 
from list l
inner join types t on t.id = l.type
where t.name in ('key2')
group by l.id
having count(distinct t.id) = 1

SQlFiddle example

like image 89
juergen d Avatar answered Mar 03 '23 19:03

juergen d