简体   繁体   English

SQL选择n到m的关系

[英]SQL select in n to m relationship

I have an n-to-m relationship between Author and Book . 我与AuthorBook之间存在Author一种从不相关的关系。

Table Author 表作者

ID       Name
1        Follett  
2        Rowling
3        Martin

Table Book 表书

ID     Title                       Category 
1        A Dance with Dragons      Fantasy
2        Harry Potter              Fantasy
3        The Key to Rebecca        Thriller
4        World without end         Drama

Table book_author 表book_author

authorId       bookId
1        3  
2        2
3        1
1        4

There are a lot more authors and books in the system. 系统中有更多的作者和书籍。 Now I want to select all authors that have a book in genre " Fantasy ". 现在我想选择所有拥有“ 幻想 ”类型书籍的作者。

This is what I came up so far with: 这是我到目前为止提出的:

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

I am wondering how to optimize this query since especially table book is really large. 我想知道如何优化这个查询,因为特别是桌面书真的很大。

It is recommended to use an explicit JOIN instead of the implicit (comma-separated table list) join you currently have, as it will improve flexibility if and when you need to introduce left joins. 建议使用显式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 has defined FOREIGN KEY relationships back to the author and books tables, indexes will be enforced. 如果book_author已将FOREIGN KEY关系定义回authorbooks表,则将强制执行索引。 Likewise, the respective id columns in those tables should be defined as PRIMARY KEY . 同样,这些表中的各个id列应定义为PRIMARY KEY Beyond this, the only potential optimization you can do is to create an index on books.category . 除此之外,您可以做的唯一潜在优化是在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)
);

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

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