检查 id 列表是否都存在于 MySQL 和 PHP 中 [英] Check if a list of ids all exist in MySQL and PHP
本文介绍了检查 id 列表是否都存在于 MySQL 和 PHP 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
MySQL
和 PHP
中检查 id 列表是否全部存在的最有效方法是什么?如果 all id 存在,我希望函数返回结果为 true
,否则 false
.
What is the most efficient way in MySQL
and PHP
to check if a list of ids all exist? I want the function return result to be true
if all ids exists, else false
.
我在想:
$ids = array(2233, 5545, 9478, 5343, 3545);
do_all_groups_exist($ids);
function do_all_groups_exist(array $ids = array()) {
if(empty($ids)) {
return true;
}
$SQL = "SELECT count(`id`) as count
FROM groups
WHERE `id` IN (" . implode(',', $ids) . ")";
...
$row = mysqli_fetch_object($result);
return (intval($row->count) === count($ids)) ? true : false;
}
有没有更好的方法?
推荐答案
可以在sql语句中得到结果
You can get result in the sql statement itself
$countids= count($ids);
$sql= "SELECT CASE WHEN (
SELECT count(id) as cnt
FROM groups
WHERE id IN (" . implode(',', $ids) . ") )=$countids
THEN 'true'
ELSE 'false' END as result"
...
$row=mysqli_fetch_array($result);
echo $row['result'];
你会从列名'result'得到结果
You will get result from coloumn name 'result'
仅当表中存在所有 id 时才会返回 true.
It will return true only when all ids exists in table.
这篇关于检查 id 列表是否都存在于 MySQL 和 PHP 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文