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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分