1

我有这个:

    $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;

如果 table_live 中存在所有 id 并返回,这将正常工作

           array([id] => 1 [moderation_date] => 2012-04-11 12:55:57)....

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

           array([id] => 3 [moderation_date] => null) 
4

1 回答 1

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

其中 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"

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

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

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

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

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

于 2012-04-19T14:03:00.773 回答