簡體   English   中英

SQL選擇n到m的關系

[英]SQL select in n to m relationship

我與AuthorBook之間存在Author一種從不相關的關系。

表作者

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

系統中有更多的作者和書籍。 現在我想選擇所有擁有“ 幻想 ”類型書籍的作者。

這是我到目前為止提出的:

   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'

如果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)
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM