Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何搜索3个不同的表并在一个查询中输出结果?_Php_Sql_Search - Fatal编程技术网

Php 如何搜索3个不同的表并在一个查询中输出结果?

Php 如何搜索3个不同的表并在一个查询中输出结果?,php,sql,search,Php,Sql,Search,我在一个网站上工作,有3个表(文章、新闻和博客),我想在一个查询中搜索。每个表至少有2列我想搜索。(职称和职务) 下面的脚本适用于单个表上的查询,但我想知道是否有办法将其修改为同时适用于所有三个表 <?php if(isset($_GET['keyword'])){ $keyword = trim($_GET['keyword']) ; $keyword = mysqli_real_escape_string($db, $keyword);

我在一个网站上工作,有3个表(文章、新闻和博客),我想在一个查询中搜索。每个表至少有2列我想搜索。(职称和职务)

下面的脚本适用于单个表上的查询,但我想知道是否有办法将其修改为同时适用于所有三个表

    <?php 

    if(isset($_GET['keyword'])){
    $keyword =  trim($_GET['keyword']) ;
    $keyword = mysqli_real_escape_string($db, $keyword);



    $query = "select title,article_post from articles where title like '%$keyword%' or article_post  like '%$keyword%'";

//echo $query;
    $result = mysqli_query($db,$query);
    if($result){
    if(mysqli_affected_rows($db)!=0){
          while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
     echo '<p> <h1 class="tite"><a href="#">'.$row['title'].'</a> </h1><br>                             '.$row['article_post'].'</p><br>'   ;
    }
    }else {
        echo 'Could not find"'.$_GET['keyword'].'"';
    }

    }
    }else {
    echo "";
    }
    ?>

您可以使用
UNION

(select title, article_post as post from articles where title like '%$keyword%' or article_post  like '%$keyword%')
UNION
(select title, news_post as post from news where title like '%$keyword%' or news_post  like '%$keyword%')
UNION
(select title, blog_post as post from articles where title like '%$keyword%' or blog_post  like '%$keyword%')

我想你正在寻找这样的:

$query = "select title,article_post 
              from articles 
              where title like '%$keyword%' or article_post  like '%$keyword%'
          UNION ALL
          Select title, news_post 
              from post 
              where title like '%$newskeyword%' or news_post like '%$otherkeyword%'
          UNION ALL
          Select ...
          ...";

尝试使用Union like进行查询:

select title,post from 
(
    select title,article_post as post from articles
    union all
    select title,news_post as post from news
    union all
    select title,blogs_post as post from blogs
) where title like '%$keyword%' or post  like '%$keyword%'

如果每个表中的列数相似,或者可以返回并搜索一定数量的列,则
UNION ALL
允许附加多个选择。