通过联结表选择具有与其关联的特定项目集的行

时间:2015-05-01 16:13:50

标签: sql join junction-table

假设我们有以下架构:

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)
);

现在我们插入一些示例数据:

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

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

让我们假设John和Jane有1和2的id,而duck和cake也有1和2的id。 让我们给约翰一个鸭子,给珍妮一个鸭子和一块蛋糕。

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);

现在,我想要做的是运行两种类型的查询:

  1. 选择同时拥有鸭子和蛋糕的客户名称(应该只返回' Jane')。
  2. 选择有鸭子和DON的客户的名字有蛋糕(应该只返回' John')。

1 个答案:

答案 0 :(得分:1)

对于列出的两种类型的查询,您可以使用EXISTS子句。下面是使用exists子句的示例查询:

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')

以下是一个工作示例:http://sqlfiddle.com/#!6/3d362/2