MySQL SELECT WHERE IN LIST 和 NOT IN LIST 在同一个 SQL 中

Adr*_* P. 1 mysql arrays select where-in

我有这个:

    $ids = "1,2,3,4,5";
    $sqlQuery = "SELECT id, moderation_date
                    FROM table_live
                    WHERE id IN (".$ids.")";

    $q = $this->CI->db->query($sqlQuery);

    if($q->num_rows() > 0) {
        foreach ($q->result() as $row) {
            $arr[] = $row;
        }
    }

    return $arr;
Run Code Online (Sandbox Code Playgroud)

如果 table_live 中存在所有 id 并返回,这一切正常

           array([id] => 1 [moderation_date] => 2012-04-11 12:55:57)....
Run Code Online (Sandbox Code Playgroud)

问题:如果我发送一个 ids 1-2-3-4-5 列表,其中只有 1-2-5 匹配 IN LIST 子句,我需要返回列表中的所有内容,对于那些与列表不匹配的空值.

           array([id] => 3 [moderation_date] => null) 
Run Code Online (Sandbox Code Playgroud)

Rol*_*man 5

生成一个外连接语句,以便您得到:

SELECT ids.id, table_live.moderation_date
FROM (select 1 id union all select 2 union all ....) ids
LEFT JOIN table_live
ON ids.id = table_live.id
Run Code Online (Sandbox Code Playgroud)

其中 ids 是一个枚举所有值的子查询,如下所示:

$ids = '1,2,3,4,5'
$subquery = 'select '.str_replace(',', ' id union all select ', $ids).''
$sql = "SELECT ids.id, table_live.moderation_date
FROM ($subquery) ids
LEFT JOIN table_live
ON ids.id = table_live.id"
Run Code Online (Sandbox Code Playgroud)

一定要选择ids.id,不是table_live.id。这样,ID 将始终显示,并且仅当 table_live 中存在相应的行时才显示 moderation_date。

另一种方法是保留查询,将结果存储在数组中,然后在 php 中合并数组,以便保留所有键,并仅在两个数组中键匹配的地方填充值。

我不确定您使用的是哪种 db 库,所以我不知道如何获取结果集的数组,但假设您将行存储在 php 数组中,使用 id 的字符串表示作为键,日期作为值,那么这段代码应该可以解决问题:

$items = array(
    '1' => NULL
,   '2' => NULL
,   ...
); 
//note: use string keys in order to merge!!
$result = array_merge($items, $resultset);
Run Code Online (Sandbox Code Playgroud)

见:http : //php.net/manual/en/function.array-merge.php