我有一个n-to-m之间的关系Author
and Book
.
表作者
ID Name
1 Follett
2 Rowling
3 Martin
桌书
ID Title Category
1 A Dance with Dragons Fantasy
2 Harry Potter Fantasy
3 The Key to Rebecca Thriller
4 World without end Drama
表 book_author
authorId bookId
1 3
2 2
3 1
1 4
系统中有更多的作者和书籍。现在我想选择所有拥有该类型书籍的作者“Fantasy".
这是我到目前为止想到的:
select distinct a.id
from author a, book b, written w
where w.authorId = a.id and w.bookId = b.id and b.category = "Fantasy";
我想知道如何优化这个查询,因为特别是表书非常大。
建议使用显式JOIN
而不是您当前拥有的隐式(逗号分隔的表列表)连接,因为如果您需要引入左连接,它将提高灵活性。
SELECT
DISTINCT a.id
FROM
author a
JOIN book_author ba ON a.id = ba.authorId
JOIN books b ON b.id = ba.bookId
WHERE b.category = 'Fantasy'
If your book_author
已定义FOREIGN KEY
关系回到author
and books
表,索引将被强制执行。同样,各自的id
这些表中的列应定义为PRIMARY KEY
。除此之外,您可以做的唯一潜在优化是创建索引books.category
.
CREATE TABLE book_author (
authorId INT NOT NULL, /* or whatever the data type... */
bookId INT NOT NULL,
/* define FK constraints in book_author */
FOREIGN KEY (authorId) REFERENCES author (id),
FOREIGN KEY (bookId) REFERENCES books (id)
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)