Mysql搜索查询两列

时间:2012-03-04 10:23:20

标签: mysql search

我正在为我的网站建立一个搜索功能,并希望通过两列搜索:标题和作者。

查询:

SELECT title, bookID, publisher, pubDate, book_image, books.authorID, authors.author FROM books, authors WHERE books.authorID = authors.authorID 
            AND title LIKE '$queryString%' OR author LIKE '$queryString%'LIMIT 5

当我按标题搜索时,这工作正常,但是当我按作者搜索时,我会获得所有书籍的列表,其中搜索作者为作者。显然这是不正确的。

如何修复此查询以成功搜索标题或作者?

3 个答案:

答案 0 :(得分:2)

尝试以下:

SELECT title, bookID, publisher, pubDate, book_image, books.authorID, authors.author 
FROM books left join  authors on  books.authorID = authors.authorID 
WHERE (title LIKE '$queryString%' OR author LIKE '$queryString%') LIMIT 5

我建议你在mysql中使用fulltext搜索。这会更快更有效率

答案 1 :(得分:0)

SELECT title, bookID, publisher, pubDate, book_image, books.authorID, authors.author 
FROM books, authors 
WHERE books.authorID = authors.authorID 
        AND (title LIKE '$queryString%' OR author LIKE '$queryString%')LIMIT 5

这应该做的工作

答案 2 :(得分:0)

尝试一下:

SELECT bk.title, bk.bookID, bk.publisher, bk.pubDate, bk.book_image, bk.authorID, au.author
FROM books bk,  authors au
WHERE bk.authorID = au.authorID AND bk.title LIKE '$queryString%' OR au.author LIKE '$queryString%' LIMIT 5