dsgdf45654 2017-05-02 17:06
浏览 68
已采纳

单个查询以在多个表中搜索并生成1个结果

I'm trying to create a power search using AJAX, that looks for results in 3 different tables and returns the answer in a single table. I have accomplished this by adding 3 calls to my database (one per table), but I feel that this is not optimal.

Users will be typing in a search field and I send what they type to a database using AJAX. This example is as simple as possible to make it easier to be understood.

Example: User Input: test.

AJAX call:

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%';

I am not explaining how I generate the table form the ajax call, because that part is solved. What I currently do in PHP is:

$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>...."

Result:

+--------------+-------+------+
| table        | name  | city |
+--------------+-------+------+
| User         | test1 | 13   |
| User         | test2 | 25   |
| Company      | testc | 13   |
| Store        | stest | 33   |
+--------------+-------+------+

Is there an easier way to achieve this, using fewer HTTP requests? Perhaps using a view?

  • 写回答

1条回答 默认 最新

  • dongshuming7131 2017-05-02 18:41
    关注

    I suppose this could simply be a comment but I can't comment so: why not use 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%'
    

    That would give you exactly your result but with just one query-string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)