gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:23 28 4
gpt4 key购买 nike

我有这个:

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

如果所有 id 都存在于 table_live 中,这就可以正常工作并返回

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

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

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

最佳答案

生成一个外连接语句,这样你就可以得到:

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 将始终显示,并且仅当相应行存在于 table_live 中时才会显示 moderation_date。

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

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

$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

关于MySQL SELECT WHERE IN LIST 和 NOT IN LIST 在同一个 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10229575/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com