简体   繁体   English

基于3个表的MySQL查询

[英]MySQL query based on 3 tables

I work with PHP. 我使用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. 在桌子的书我有book_name与书的名字, book_publisher该发布者的ID和book_author与作者的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. 除了books表,我还有带作者名称和ID的books_author表,以及带书出版者名称和ID的books_publisher

I give my users 3 input fields that represents author name, book name and publisher name and a search button. 我为用户提供3个输入字段,分别代表作者姓名,书名和出版商名称以及一个搜索按钮。 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. 他们可以在同一搜索中输入作者姓名,书名和出版商名,我必须查询我的数据库并返回已输入作者名LIKE(%..%)的作者姓名的书名,书名类似于输入的书名称和发布者名称喜欢输入的发布者名称。

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). 问题是我只在图书表中存储了作者ID和出版商ID,并且我需要按所有三个字段进行搜索并排除重复项(按名称和出版商匹配的书)。

Can anybody help me building this query ? 有人可以帮我建立此查询吗?

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. 通常,在这些情况下,搜索框是可选的,因此您需要动态构造查询,这意味着WHERE子句仅在用户实际输入发布者名称时才对发布者名称进行过滤。

Also, searching on LIKE '%blah%' is not scalable beyond thousands or possibly tens of thousands of records. 同样,对LIKE '%blah%'搜索不能扩展到成千上万甚至上万条记录。 No indexing can cater for that. 没有索引可以满足此要求。 You may want to look into using something like the MySQL full-text searching instead. 您可能想研究使用类似MySQL全文搜索的方法

Lastly, make sure you sanitize your input, meaning pass all your input fields through mysql_real_escape_string() . 最后,确保清理输入,这意味着将所有输入字段通过mysql_real_escape_string()传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM