【问题标题】:selecting multiple categories from database从数据库中选择多个类别
【发布时间】:2015-12-06 04:37:48
【问题描述】:

我正在开发一个博客系统,其中博客被分类,我们可以选择我们想要的类别。为此,我必须将表 blogscategories 分开。我知道如何从所有类别和单个类别中获取博客,但我不知道如何从多个但不是所有类别中获取博客。

我的代码如下所示:

 <?php
   $query = ("SELECT blogs_id, title, body, posted_by, category FROM blogs INNER JOIN categories ON categories.category_id=blogs.category_id where category='cat1' ORDER BY blogs_id desc LIMIT 10");
   $result = mysql_query($query) or die("error:".mysql_error());
    while ($row = mysql_fetch_assoc($result)) {
        $title = $row['title'];
        $body = $row['body']; 
        $posted_by = $row['posted_by'];
      ?>

此代码用于选择单个类别并且效果很好,但现在我想选择多个(但不是全部)类别。我尝试了几个不同的选项,但都失败了:

 <?php
$query = ("SELECT blogs_id, title, body, posted_by, category FROM blogs INNER JOIN categories ON categories.category_id=blogs.category_id where category='cat1' AND category='cat2' AND category='cat3' ORDER BY blogs_id desc LIMIT 10");

这不起作用。

【问题讨论】:

    标签: php mysql wordpress blogs categories


    【解决方案1】:

    使用IN 子句:

    WHERE category IN ('cat1', 'cat2', 'cat3')
    

    或者,您可以使用OR

    WHERE category = 'cat1'
       OR category = 'cat2'
       OR category = 'cat3'
    

    【讨论】:

      【解决方案2】:

      尝试使用OR 代替AND(在 where 条件下)。试试这个:

      $query = ("SELECT blogs_id, title, body, posted_by, category FROM blogs INNER JOIN categories ON categories.category_id=blogs.category_id where category='cat1' OR category='cat2' OR category='cat3' ORDER BY blogs_id desc LIMIT 10");
      

      【讨论】:

        【解决方案3】:

        试试这个

        $query = ("SELECT blogs_id, title, body, posted_by, category FROM blogs INNER JOIN categories ON categories.category_id=blogs.category_id where category IN ('cat1', 'cat2', 'cat3') ORDER BY blogs_id desc LIMIT 10");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-29
          • 1970-01-01
          • 2010-10-15
          相关资源
          最近更新 更多