繁体   English   中英

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

[英]How can I search 3 different tables and output the results in one query?

我正在一个网站上工作,有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,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

(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%')

我认为您正在寻找像这样的UNION

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM