php - 关于将搜索多个表的搜索功能的建议? - PHP/MySQL

标签 php mysql search

在我的网络应用程序中,我计划包含一个允许用户输入字符串的搜索字段。

此字符串随后将用于与多个表中的数据行进行比较,例如在此数据库中。 (这只是一个例子,在实际问题中大约有20张表)。

表格列表:

  • 客户
  • 书籍
  • 绘画

什么是最好的搜索方式,因为这是我第一次搜索多个表?

您是按顺序浏览表格,将每一行与搜索字符串进行比较,还是可以进行一般搜索整个数据库的查询?

是应该在找到完全匹配项后停止搜索,还是不管是否找到匹配项都继续搜索?如果有多个相同类型的行?

我想以最“正确”的方式做到这一点我看过一些例子,但它们似乎只与一两个表搜索有关。

我脑子里有这个伪代码,如果你也能给我反馈的话,我可能会这样做

Get string from $_POST['search'] 
Strip string of special characters that could be used for Mysql injection.
Connect to db 
Search first table for row that is LIKE string
If match found then add to result object
Search next table, and repeat.
When finished search disconnect from DB.

所以我希望你们能够指导我链接到 Material ,以便我可以尽可能最好地实现这一功能。

谢谢你:)

最佳答案

首先,让您知道,如果搜索条件是“包含”但不是starts with,这将成为性能非常差的搜索。此外,所有可搜索列都需要索引。

嗯,执行此查询的最简单方法是使用所有搜索字段的并集创建一个大 View :

create view my_search as (
   select 
     id_customer as key, 
     customer_name as value, 
     'customers' as table,
     1 as priority
   from customer
   UNION ALL
   select 
     id_customer as key, 
     customer_alternate_name as value, 
     'customers' as table,
     2 as priority
   from customer
   UNION ALL
   ...
   UNION ALL
   select 
     id_Paintings as key, 
     Paintings_name as value, 
     'Paintings' as table,
     8 as priority
   from Paintings
)

然后对 View 执行查询:

select * from my_search
 where value like ...
 order by priority 

请注意,这不能解决您仅从出现字符串的第一个表中获取结果的要求,您可以在发现优先级更改时停止 php 获取行。

关于php - 关于将搜索多个表的搜索功能的建议? - PHP/MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8969555/

相关文章:

php - 清理多余的 PHP 扩展 - 将所有内容切换到 mcrypt 或 openssl?

php 正则表达式,末尾带有可选字符

mysql - 是否可以模拟MySQL复制SlaveIO和SlaveSQL崩溃来测试监控脚本?

mysql - 无法通过命令行连接本地MySQL数据库?

javascript - 如何创建搜索语言?

search - Elasticsearch定制词干算法

php - 超出执行时间

php - 使用 fgetcsv 遍历 csv

mysql - 在 MYSQL 中,GROUP BY 之后在几个字段中选择最常出现的值

MySQL:SEARCH 查询中的 mysql_real_escape_string