我应该使用加入还是使用单独的查询

时间:2015-12-22 05:46:21

标签: php mysql join

Table 1: book(bookid(pk),bookname,edition)
Table 2: bookinfoauthors(bookid(fk), authorid(fk))
Table 3: author(authorid(pk), authorname)

我有一个AuthorNames数组,我想获得这些作者编写的相应bookName AuthorNames可能包含一个或多个名称

我正在使用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);

在第二种风格中,我没有使用一个有效的连接,我应该遵循什么

1 个答案:

答案 0 :(得分: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子句中,这使得它更难以阅读。