2015-12-22 45 views
1
Table 1: book(bookid(pk),bookname,edition) 
Table 2: bookinfoauthors(bookid(fk), authorid(fk)) 
Table 3: author(authorid(pk), authorname) 

我有AuthorNames的陣列我想通過這些作者撰寫相應BOOKNAME AuthorNames可能含有1個或多個名稱我應該用加入或使用單獨的查詢

我使用PHP和MySQL數據庫

風格1:

select book.bookName 
from book, bookauthors, author 
where (book.bookid = bookoauthors.bookid) 
and (author.authorid = bookauthor.authorid) 
and (author.authorName = Authornames[0]) 
or (author.authorName = Authornames[1]) 
or (author.authorName = Authornames[2]) 
or (author.authorName = Authornames[3]) 

,因爲我使用PHP我的MySQL; 樣式2: //假設$的AuthorID,$ BOOKID,$ BOOKNAME包含int或字符串數​​組不是對象

$authorId = 
    select authorId 
    from authors 
    where authorName in ($authorNames); 

$bookId = select bookid from bookAuthors where bookName in($authorId); 
$bookName = select bookName from book where bookid in (bookId); 

在第二種風格,我不使用連接哪一個將是有效的,我應該遵循

+3

使用連接..它很快然後正常查詢 –

回答

2

首先我想說,你幾乎肯定會寧願做一個單一的JOIN查詢來獲得一個結果集,而不是對你的MySQL數據庫進行多種不同的調用。 MySQL被設計用於繁重的數據提取; PHP遠不如此。在後一種情況下,網絡流量花費的時間可能會很長,影響您網站的性能。

其次,您應該嘗試使用兼容ANSI-92的SQL查詢。因此,我將重寫JOIN查詢,因爲這:

SELECT b.bookName 
FROM book b INNER JOIN bookauthors ba ON b.bookid = ba.bookid 
      INNER JOIN author a ON a.authorid = ba.authorid 
WHERE a.authorName = Authornames[0] OR 
     a.authorName = Authornames[1] OR 
     a.authorName = Authornames[2] OR 
     a.authorName = Authornames[3] 

這種風格的查詢是首選的原因是,它分離從WHERE子句中的其他限制表的連接。在原始查詢中,連接標準和限制都出現在WHERE條款中,使其難以閱讀。

+0

謝謝我真的認爲第二個會更好 –

相關問題