php - 如何让 SELECT...WHERE IN 为 AND 而不仅仅是 OR 工作?

标签 php mysql

我有 3 个 MySQL 表:

blog_posts // Contains blog posts
blog_tags // Contains tags
rel__blog_post_tags // Relates tags to a blog post (refering relation IDs)

这是我的 PHP 代码:

// I get tags from URL: /tag/tag1;tag2;tag3
$tags = explode(';', $options['req_tags']);
// Prepare for prepared SQL query
$in = str_repeat('?,', count($tags) - 1) . '?';
// Prepare SQL param array as I need to mix category ID with tags...
$sql_params = $tags;

// This SQL will select with IN (equals to OR but want to change to AND)
$sql_get_posts = '
    SELECT * FROM blog_posts
    WHERE category_id = ?
    AND post_id IN
        (SELECT post_id FROM rel__blog_post_tags
            WHERE tag_id IN (' . $in . '));';

// Prepare the query
$get_posts = $PDO->prepare($sql_get_posts);
// Add category ID to beginning of array of SQL params (in front of tags)
array_unshift($sql_params, $options['category_id']);

// Now execute and get blog posts to array
$get_posts->execute($sql_params);
$postdata = $get_posts->fetchAll();

?>

好的,所以我的问题是我使用“WHERE tag_id IN ...”。这将返回任何匹配的博客文章:

...AND post_id IN (SELECT post_id FROM rel__blog_post_tags WHERE tag_id='tag1' OR tag_id='tag2' OR tag_id='tag3'... and so on.

所以基本上,我无法通过添加更多标签来缩小我的博文结果,这正是我所追求的。

我如何更改此 SQL 查询以使其像下面这样,这样如果我有一个 ID 为“foobar”的博客文章并且它与数据库中的 tag1 和 tag2 有连接,它就不会出现,因为我正在寻找 ID 为“foobar”且具有标签 tag1、tag2 和 tag3 的博客文章:

...AND post_id IN (SELECT post_id FROM rel__blog_post_tags WHERE tag_id='tag1' AND tag_id='tag2' AND tag_id='tag3'... And so on...

最佳答案

您可以通过创建“and tag_id=?”的集合来修复它使用 for 循环的字符串。 如下图所示:

for($i=0; $i<count($tags);$++){
if($i=0){
$condition="tag_id=$tags[$i]";
}
else{
$condition.="and tag_id=$tags[$i]";
}

}

关于php - 如何让 SELECT...WHERE IN 为 AND 而不仅仅是 OR 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29190974/

相关文章:

php - Laravel 验证所有页面

php - 从数组中创建具有重复值的数组 (PhP)

php - 交响乐 2.8 : concept of container scopes is deprecated

php - 查找具有静态最大日期和最小日期的每日 session 的平均值

MySQL LOAD DATA LOCAL INFILE 与 SQL 文件

php - Silex,安全防火墙和自定义用户提供商的不良凭据

php - 如何从 PHP 中的两个不同数组获取公共(public)值

php - MySQL 返回具有递增计数的行的多个副本

php - 是否可以知道 php 中的(服务器)CPU 性能?

php - Eloquent 创建了错误的查询