dpps0715 2014-12-13 12:03
浏览 40
已采纳

如何使用mysql数据库数据删除php上的数组上的项目

I want to do something like this


----sql output----
name TEXT
b
c


$arr = ["a","b","c","d"];

foreach($arr as $key=>$val){
    $query = "select count(*) from mydata where name = $val";
    $count = xxxx($query);
    if($count)unset($arr[$key]);
}

And $arr will be
a,d

Any simple way to do it but not checking every single element?


---edited---
I think I solve my problem myself...getting some inspired from mrlore that using having.

$arr = ["a","b","c","d"]; /* make the string inside arr safe for query */
$val = array_map(function($val){return "'$val'";},$arr);
$q = "select name from mydata where name in (" . implode(',',$val) .")";
$all = xxxxx($q);
$arr = array_diff($arr,$all);

This took me 0.8 second. Using my old way take 46 second and RST way takes 2 seconds.


---edited----
I have over 200k rows of data in my database, so I want a better way to optimize it.


--re MrLore--
ps : I don't know how to use stackoverflow to posting comments..so I just edit my post.

I have tried it on my mysql workbench but it does not seem to work for me.

select name from mydata  
where name in("a","b","c","d")  
having count(name) = 0  

-- returns nothing

select name from mydata  
where name in("a","b","c","d")  
having count(name) > 0  
  • 写回答

1条回答 默认 最新

  • drduh44480 2014-12-13 12:18
    关注
    $arr = ["a","b","c","d"];
    
        $query = "select DISTINCT name from mydata";
        $results = <result of query>;
    
        foreach ($results as $result){
          if(($key = array_search($result, $arr)) !== false) {
            unset($arr[$key]);
          }
        }
    

    Or the other way around

        foreach ($arr as $key=>$value){
          if( in_array( $value, $results) ) {
            unset($arr[$key]);
          }
        }
    

    By querying DISTINCT the database only returns unique values. You can then compare them with the array you have and remove them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建