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

时间:2011-12-14 07:21:33

标签: php sql search

我正在网站上工作,并且有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 "";
    }
    ?>

3 个答案:

答案 0 :(得分:1)

尝试使用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%'

答案 1 :(得分:0)

您可以使用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%')

答案 2 :(得分:0)

我认为您正在寻找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 ...
          ...";