SQL选择n到m的关系

时间:2012-10-10 16:26:59

标签: sql

我在AuthorBook之间存在 n-to-m 关系。

表作者

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

我想知道如何优化此查询,因为特别是桌面书很大。

1 个答案:

答案 0 :(得分:7)

建议使用显式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'

如果您的book_author已将FOREIGN KEY关系定义回authorbooks表,则会强制执行索引。同样,这些表中的相应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)
);
相关问题