如何交叉两个结果集?

时间:2016-02-17 11:40:57

标签: mysql resultset

我有两个表librarybook,如这两个块

所示
bookid   title  author  publisher 
0        ABC    Abc     abc 
1        DEF    Def     def
2        GHI    Ghi     abc
3        ...    ...     ...

id       discount   price
0         50          8
1         75          6
2         33         10
3         ..         ..

我需要选择每个作者的作品,价格和折扣,其中出版商至少有2个标题,不超过9个。 第一个查询可能是

SELECT title, author, publisher, price, discount FROM library, book

这是一个清晰的返回所有数据。第二个查询可能是

SELECT publisher FROM library GROUP BY publisher 
HAVING COUNT(bookid) > 2 AND COUNT(bookid) < 9

这没关系,但它不会返回作者,标题和价格。我想交叉两个结果集。我尝试过以下查询

SELECT title, author, publisher, price, discount FROM library LEFT JOIN
book ON library.bookid = book.id WHERE publisher IN ( SELECT publisher
FROM library GROUP BY publisher HAVING COUNT(bookid) < 9 AND 
COUNT(bookid) > 2 ) ORDER BY publisher ASC

输出应为:

Title  Author  Publisher Price   Discount
ABC    Abc     abc       8       ...
GHI    Ghi     abc       10      ...
...    ...     def       11      ...
...    ...     def       11      ...
...    ...     def       9       ...

它工作正常但在100条记录上速度非常慢,当记录超过1000条时它根本不起作用。如何优化查询? 提前致谢

1 个答案:

答案 0 :(得分:0)

这基本上是您的查询:

SELECT l.title, l.author, l.publisher, b.price, b.discount
FROM library l LEFT JOIN
     book b
     ON l.bookid = b.id
WHERE l.publisher IN (SELECT l.publisher
                      FROM library l
                      GROUP BY l.publisher
                      HAVING COUNT(*) < 9 AND COUNT(*) > 3
                     )
ORDER BY l.publisher ASC;

首先,我将IN逻辑移到FROM子句:

SELECT l.title, l.author, l.publisher, b.price, b.discount
FROM library l LEFT JOIN
     book b
     ON l.bookid = b.id JOIN
     (SELECT l.publisher
      FROM library l
      GROUP BY l.publisher
      HAVING COUNT(*) < 9 AND COUNT(*) > 3
     ) ll
     ON l.publisher = ll.publisher
ORDER BY l.publisher ASC;

然后,我认为这些索引可以帮助book(id)library(publisher, bookid)