doujiene2845 2015-03-22 04:22
浏览 338
已采纳

如何使SELECT ... WHERE IN用于AND而不仅仅是OR?

I have 3 MySQL tables:

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

This is my PHP code:

// 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();

?>

OK so my problem here is that I use "WHERE tag_id IN...". This will return any blog posts that matches:

...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.

So basically, I cannot narrow down my blog post results by adding more tags, which is what I am after.

How can I change this SQL query to make it so that it will be like the below, so that if I have a blog post with ID "foobar" and it has a connection with tag1 and tag2 in the database it will not show up, as I am looking for blog post with ID "foobar" that has tag tag1, tag2 AND 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...
  • 写回答

3条回答 默认 最新

  • duanqianpu6499 2015-03-22 05:10
    关注

    You can fix it by creating the set of "and tag_id=?" string using for loop. Like shown below:

    for($i=0; $i<count($tags);$++){
    if($i=0){
    $condition="tag_id=$tags[$i]";
    }
    else{
    $condition.="and tag_id=$tags[$i]";
    }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大