从数据库中选择多个类别

时间:2015-09-10 03:23:23

标签: php mysql wordpress blogs categories

我正在开发一个博客系统,对博客进行分类,我们可以选择我们想要的类别。为此,我必须将表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");

这没有用。

2 个答案:

答案 0 :(得分:4)

使用IN子句:

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

或者,您可以使用OR

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

答案 1 :(得分:3)

尝试OR代替AND(在哪里条件下)。试试这个:

$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");
相关问题