B
B
bestauction2020-05-29 13:44:35
SQL
bestauction, 2020-05-29 13:44:35

How to make a SQL query on three tables?

You need to select products that have ALL possible tags from the database. In this case, the answer should be Bread. On sqlite

Base example

SQL source

CREATE TABLE product (id INTEGER, name TEXT);

INSERT INTO product  (id, name)
VALUES
    (1, 'Beer'),
    (2, 'Bread'),
    (3, 'Chease'),
    (4, 'Water');

CREATE TABLE labels (id INTEGER, name TEXT);

INSERT INTO labels (id, name)
VALUES
    (1, 'Nice'),
    (2, 'Bad'),
    (3, 'Normal'),
    (4, 'Lol');

CREATE TABLE labels_products (label_id INTEGER, product_id INTEGER, UNIQUE (label_id, product_id));

INSERT INTO labels_products (label_id, product_id)
VALUES 
    (1, 1),
    (2, 1),
    (3, 1),
    (4, 1),
    (1, 3),
    (2, 2),
    (3, 3);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
d-stream, 2020-05-29
@bestauction

select 
  product.id
from product
inner join labels_products on labels_products.product_id=product.id
inner join labels onlabels.id=labels_products.label_id
group by product.id
having count(product.id)=(select count(*) from labels)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question