Select rows that have a specific set of items associated with them through a junction table

浪尽此生 提交于 2019-12-13 05:48:21

问题


Suppose we have the following schema:

CREATE TABLE customers(
    id INTEGER PRIMARY KEY, 
    name TEXT
);
CREATE TABLE items(
    id INTEGER PRIMARY KEY, 
    name TEXT
);
CREATE TABLE customers_items(
    customerid INTEGER, 
    itemid INTEGER, 
    FOREIGN KEY(customerid) REFERENCES customers(id),
    FOREIGN KEY(itemid) REFERENCES items(id)
);

Now we insert some example data:

INSERT INTO customers(name) VALUES ('John');
INSERT INTO customers(name) VALUES ('Jane');

INSERT INTO items(name) VALUES ('duck');
INSERT INTO items(name) VALUES ('cake');

Let's assume that John and Jane have id's of 1 and 2 and duck and cake also have id's of 1 and 2. Let's give a duck to John and both a duck and a cake to Jane.

INSERT INTO customers_items(customerid, itemid) VALUES (1, 1);
INSERT INTO customers_items(customerid, itemid) VALUES (2, 1);
INSERT INTO customers_items(customerid, itemid) VALUES (2, 2);

Now, what I want to do is to run two types of queries:

  1. Select names of customers who have BOTH a duck and a cake (should return 'Jane' only).
  2. Select names of customers that have a duck and DON'T have a cake (should return 'John' only).

回答1:


For the two type of queries listed, you could use the EXISTS clause. Below is an example query using the exists clause:

SELECT cust.name 
from customers AS cust
WHERE EXISTS (
     SELECT 1
     FROM items
     INNER JOIN customers_items ON items.id = customers_items.itemid
     INNER JOIN customers on customers_items.customerid = cust.id
     WHERE items.name = 'duck')
AND NOT EXISTS (
     SELECT 1
     FROM items
     INNER JOIN customers_items ON items.id = customers_items.itemid
     INNER JOIN customers on customers_items.customerid = cust.id
     WHERE items.name = 'cake')

Here is a working example: http://sqlfiddle.com/#!6/3d362/2



来源:https://stackoverflow.com/questions/29990684/select-rows-that-have-a-specific-set-of-items-associated-with-them-through-a-jun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!