计算与IN子句中的所有值匹配的所有行

时间:2018-02-05 15:24:22

标签: php mysql

我的$topics的值为1,2,3我想创建一个类似于SELECT COUNT(*) FROM subtopics WHERE main_id = 1 AND main_id = 2 and main_id = 3..的选择查询

    function countTopics($mid,$forum){
    $topics = implode(', ', array_column($mid, 'main_id'));
    parse_str("id=1");
    $query = "SELECT COUNT(*)
                FROM subtopics
               WHERE main_id   
                  IN ($topics)
                  GROUP BY main_id
                  HAVING COUNT(DISTINCT $topics) = 3";
    $stmt = $forum->prepare($query);
    $stmt->execute(array(
        'mid' => $topics
    ));
    $rows = $stmt->fetchAll();
    $count = implode(', ', array_column($rows, 'COUNT(*)'));
    $_SESSION['topics_count'] = $count;
}

1 个答案:

答案 0 :(得分:0)

代码存在各种问题,您的SQL不需要HAVING子句,您尝试绑定到SQL语句中不存在的变量...

function countTopics($mid,$forum){
    $topics = implode(', ', array_column($mid, 'main_id')); 
    $query = "SELECT main_id, COUNT(*) as countID
            FROM subtopics
            WHERE main_id IN ($topics)
            GROUP BY main_id";
    if ( $stmt = $forum->prepare($query) ) {
        if ( $stmt->execute() ) {
            $rows = $stmt->fetchAll();
            $count = implode(', ', array_column($rows, 'countID'));
            $_SESSION['topics_count'] = $count;
        }
     }
}

此外,你应该检查前一阶段是否有效 - 所以'如果声明准备工作'不确定如果其中任何一个失败你会怎么做,但这取决于你的应用程序设计。

不确定$forum是什么,因为它似乎没有被使用,返回计数值并让调用代码决定如何处理该值更为正常。

您可能想要做类似......

的事情
    $rows = $stmt->fetchAll();
    $_SESSION['topics_count'] = $rows;

然后再......

foreach ( $_SESSION['topics_count'] as $topic ) {
   echo $topic['main_id'].'-'.$topic['countID'].PHP_EOL;
}

更新

function countTopics($mid,$forum){
    $topics = implode(', ', array_column($mid, 'main_id')); 
    $query = "SELECT main_id, subtopic_id, COUNT(*) as countID
            FROM subtopics
            WHERE main_id IN ($topics)
            GROUP BY main_id, subtopic_id";
    if ( $stmt = $forum->prepare($query) ) {
        if ( $stmt->execute() ) {
            $rows = $stmt->fetchAll();
            $_SESSION['topics_count'] = $rows;
        }
     }
}

我添加了名为' subtopic_id'的列,可能需要根据您的数据库列名称进行更改。这将为行提供类似......

main_id   subtopic_id countID
1         1            12
1         2            6
1         3            10
2         6            1
2         11           3

这意味着每个main_id都有多行,但它们将包含每个子主题和该子主题的计数。如果要输出数据 - 您必须使用循环,如上面的foreach