猿问

如果使用 MySQL IN 语句从数组中找不到匹配项,则返回 0

我知道有很多类似的问题和答案,但在这种情况下,它们都不起作用,因为我使用IN语句从数组中获取匹配项,而我的日期varchar由于其格式而采用数据类型。这里是:


我正在尝试检查数据库中是否存在数组项,并将每个项的计数作为一个数组。我的 SQL 查询运行良好并获得结果,但唯一的问题是我希望它为数据库中不存在的数组项返回 0 而不是跳过它。


例如,这里是我的数据库表:


postId   reactedTo   reactedDate

126      Like        22 Jun 2019

172      Haha        24 Jun 2019

172      Wow         27 Jun 2019

132      Like        27 Jun 2019

这是我运行 SQL 查询并将结果作为数组获取的函数


public function reactionsAnalytics() {

    global $wpdb;

    $tableName = $wpdb->prefix.'reactions';

    $dates = $this->getLastNDays(7); //array('22 Jun 2019', '23 Jun 2019', ... ,'28 Jun 2019');

    $reacts = $wpdb->get_results("

SELECT reactedDate, count(*) AS count

  FROM {$tableName} 

 WHERE reactedDate IN ('".implode("','", $dates)."')  

 GROUP 

    BY reactedDate

", ARRAY_A);


    $result = array();

    foreach ($reacts as $react) {

        $result[] = $react['count'];        

    }


    wp_die(json_encode($result));

}

这个函数的预期输出是 ["1","0","1","0","0","2","0"],但我得到 ["1","1" ,"2"]。如何防止 $reacts 查询跳过未找到的项目并使其输出 0?


我试过使用COALESCE,IFNULL并SUM有各种变化,但得到了相同的结果,但没有零。


这是 SQL Fiddle,您可以使用它:


http://sqlfiddle.com/#!9/ffbb98/5


慕运维8079593
浏览 498回答 1
1回答

呼啦一阵风

无需尝试使查询复杂化,您只需稍微更改应用程序 (PHP) 代码即可。获取数据库中可用日期的查询结果。现在,在 PHP 代码中,只需检查该日期的计数是否可用。如果是,使用计数,否则设置为零。// Change the SQL query result to an array with date as key, and count as value$reacts_mod = array_combine(array_column($reacts, 'reactedDate'),                             array_column($reacts, 'count'));// Now prepare the $result$result = array();// Loop over input dates hereforeach ($dates as $dt) {    // If you have count obtained from the query result, then consider that else 0    if ( isset($reacts_mod[$dt]) ) {        $result[] = $reacts_mod[$dt];    } else {        $result[] = 0;    }    // Note: PHP7 code would be simply:    // $result[] = $reacts_mod[$dt] ?? 0;}
随时随地看视频慕课网APP
我要回答