我尝试使用AJAX创建强力搜索,它在3个不同的表中查找结果并在单个表中返回答案。我通过向我的数据库添加3个调用(每个表一个)来完成此操作,但我觉得这不是最佳选择。
用户将在搜索字段中键入内容,然后使用AJAX将他们键入的内容发送到数据库。这个例子尽可能简单易懂。
示例: 用户输入:测试。
AJAX电话:
SELECT 'User' AS table, f_name AS `name`, city FROM people WHERE f_name LIKE '%test%';
SELECT 'Company' AS table, `name`, city FROM companies WHERE `name` LIKE '%test%';
SELECT 'Store' AS table, `name`, city FROM stores WHERE `name` LIKE '%test%';
我没有解释如何从ajax调用生成表,因为该部分已经解决。我目前在PHP中做的是:
$sql = SELECT .... FROM people ....;
$res = mysqli...
while($row = mysqli_fetch...) {
echo "<tr><td>{$row[table]}</td>...."
$sql = SELECT .... FROM companies ....;
$res = mysqli...
while($row = mysqli_fetch...) {
echo "<tr><td>{$row[table]}</td>...."
$sql = SELECT .... FROM stores ....;
$res = mysqli...
while($row = mysqli_fetch...) {
echo "<tr><td>{$row[table]}</td>...."
结果:
+--------------+-------+------+
| table | name | city |
+--------------+-------+------+
| User | test1 | 13 |
| User | test2 | 25 |
| Company | testc | 13 |
| Store | stest | 33 |
+--------------+-------+------+
使用更少的HTTP请求是否有更简单的方法来实现这一目标?也许使用视图?
答案 0 :(得分:0)
我想这可能只是一个评论,但我不能发表评论:为什么不使用UNION
?
SELECT 'User' AS table, f_name AS `name`, city FROM people WHERE f_name LIKE '%test%'
UNION
SELECT 'Company' AS table, `name`, city FROM companies WHERE `name` LIKE '%test%'
UNION
SELECT 'Store' AS table, `name`, city FROM stores WHERE `name` LIKE '%test%'
这样可以准确地给出结果,但只有一个查询字符串。