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

单个查询以在多个表中搜索并生成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 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据