从数据库中选择多个类别
selecting multiple categories from database
我正在开发一个博客系统,其中对博客进行了分类,我们可以选择我们想要的类别。为此,我必须将表 blogs
和 categories
分开。我知道如何从所有类别和单个类别中获取博客,但我不知道如何从多个但不是所有类别中获取博客。
我的代码如下所示:
<?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");
这没有用。
使用IN
子句:
WHERE category IN ('cat1', 'cat2', 'cat3')
或者,您可以使用 OR
:
WHERE category = 'cat1'
OR category = 'cat2'
OR category = 'cat3'
尝试用 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");
试试这个
$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");
我正在开发一个博客系统,其中对博客进行了分类,我们可以选择我们想要的类别。为此,我必须将表 blogs
和 categories
分开。我知道如何从所有类别和单个类别中获取博客,但我不知道如何从多个但不是所有类别中获取博客。
我的代码如下所示:
<?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");
这没有用。
使用IN
子句:
WHERE category IN ('cat1', 'cat2', 'cat3')
或者,您可以使用 OR
:
WHERE category = 'cat1'
OR category = 'cat2'
OR category = 'cat3'
尝试用 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");
试试这个
$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");