tags:

views:

101

answers:

1

Hello. I work with PHP. I have a table named books. In table books I have the book_name with the name of the book, book_publisher with the publisher's ID and book_author with the author's ID. Besides the books table I have the books_author table with the authors names and IDs and books_publisher with the books publishers names and IDs.

I give my users 3 input fields that represents author name, book name and publisher name and a search button. They can input an author name, a book name and publisher name in the same search and I have to query my database and return the books names that have author name LIKE (%..%) inputted author name, book name LIKE the inputted book name and publisher name LIKE the inputted publisher name.

The problem is that I have stored only the author's id and publisher's id in my books table and I need to search by all three fields and exclude duplicates (books that were match by name and also by publisher).

Can anybody help me building this query ?

+6  A: 

Just join the query:

SELECT *
FROM books b
JOIN book_authors ba ON b.author_id = ba.id
JOIN book_publishers bp ON b.publisher_id = bp.id
WHERE b.book_name LIKE '...'
AND ba.author_name LIKE '...'
AND bp.publisher_name LIKE '...'

Usually in these situations the search boxes are optional so you'll need to dynamically construct the query, meaning the WHERE clause to only filter on, say, publisher name if the user actually entered a publisher name.

Also, searching on LIKE '%blah%' is not scalable beyond thousands or possibly tens of thousands of records. No indexing can cater for that. You may want to look into using something like the MySQL full-text searching instead.

Lastly, make sure you sanitize your input, meaning pass all your input fields through mysql_real_escape_string().

cletus
+1 for the full-text searching suggestion
karim79
Even better is indexing the text fields with Sphinx Search. I understand it's a lot faster than MySQL's built-in full-text indexing, supports stemming, etc.
Bill Karwin
THANK YOU VERY MUCH!
Manny Calavera