简体   繁体   English

从数据库中获取已订购两本特定书籍的客户

[英]Getting customers that have ordered two specific books from the database

Consider a database has these three tables, 考虑一个数据库具有这三个表,

Book ( bookId , isbn, title, url, ... ) 图书bookId ,isbn,书名,URL等)

Customer ( customerId , name, email, phone) 客户customerId ,名称,电子邮件,电话)

Order ( bookId , customerId , quantity, date) 订单bookIdcustomerId ,数量,日期)

What i'm trying to do is, to get the customers who have ordered two specific books named "BOOK A" and "BOOK B" . 我正在尝试做的是让订购了两本名为"BOOK A""BOOK B"特定书籍的客户。

I came up with a query like this : 我想出了这样的查询:

SELECT o.customerId
FROM Book b, Order o
WHERE o.bookId = b.bookId
AND  b.title in ("BOOK A", "BOOK B");

Which resulted the customers who have ordered at least one of the two books i have specified. 这导致订购我指定的两本书中至少一本书的客户。

Any help is appreciated. 任何帮助表示赞赏。

SELECT o.customerId
FROM Book b, Order o
WHERE o.bookId = b.bookId
AND  b.title in ("BOOK A")
AND EXISTS (select 1 from Book bb, Order oo 
            where oo.bookId = bb.bookId
            and oo.customerId = o.customerId
            and bb.title in ("BOOK B"))
SELECT o.customerId
FROM Order o
WHERE (SELECT count(distinct b.bookId)
         FROM Book b
       WHERE o.bookId = b.bookId
         AND  b.title in ('BOOK A', 'BOOK B')
      ) = 2;

This essentially checks that the number of books per order, restricted to "BOOK A" and "BOOK B" is 2, ie both books must be in the same order . 这实质上检查了每个订单的书籍数量(仅限于“ BOOK A”和“ BOOK B”)是否为2,即,两本书的顺序必须相同

If you want to look for the books in any order of the same customer, you need a second instance of order : 如果你想寻找的书籍在同一客户的任何命令,你需要的第二个实例order

SELECT o.customerId
FROM Order o
WHERE (SELECT count(distinct b.bookId)
         FROM Book b JOIN Order oo ON oo.bookId = b.bookId
       WHERE o.customerId = oo.customerId
         AND  b.title in ('BOOK A', 'BOOK B')
      ) = 2;

This could be optimized, assuming a table Customer : 假设有一个表Customer ,可以对此进行优化:

SELECT c.customerId
FROM Customer c
WHERE (SELECT count(distinct b.bookId)
         FROM Book b JOIN Order oo ON oo.bookId = b.bookId
       WHERE c.customerId = oo.customerId
         AND  b.title in ('BOOK A', 'BOOK B')
      ) = 2;

This would avoid duplicate customers in the result, and join smaller tables, hence should be faster. 这样可以避免结果中出现重复的客户,并加入较小的表,因此应该更快。

All three solutions can easily be extended to three, four ... books. 所有这三种解决方案都可以轻松扩展到三,四本……书。 Just enumerate them in the IN and adapt the count. 只需在IN枚举它们并调整计数即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM