【问题标题】:Looping through array and searching a database for a match遍历数组并在数据库中搜索匹配项
【发布时间】:2012-12-03 21:27:18
【问题描述】:

每天我都会收到一个带有电话号码的 csv 文件。我已经构建了一个从 csv 中获取数据的数组。我需要做的是遍历数组并在 mysql 数据库中搜索匹配项。你的一位大师能不能给我指出正确的方向?

【问题讨论】:

    标签: mysql arrays loops


    【解决方案1】:

    我建议创建临时表,然后将您的号码加载到此表中,然后只需选择并加入您的表即可。您可以在程序中插入手机(一个INSERT 中的多行,或者如果您可以访问服务器外壳,您可以执行以下脚本:

    -- you can use TEMPORARY table in one transaction or you can just
    -- make sure that the table exists and flush it before import
    
    CREATE TABLE IF NOT EXISTS phonenumbers (
        number varchar(10) primary key
    );
    
    TRUNCATE TABLE phonenumbers;
    
    LOAD DATA LOCAL INFILE 'numbers.csv' INTO TABLE phonenumbers;
    
    -- here in script or call it from your program to work with data
    -- also you can add  INTO OUTFILE 'output.csv' to export filtered data
    -- into outfile 
    
    SELECT addressbook.* FROM addressbook LEFT JOIN phonenumbers on (addressbook.phone = phonenumbers.number);
    

    【讨论】:

      【解决方案2】:

      如果可以,请使用 LOAD DATA 将 csv 导入临时表,然后编写一个查询,将该表与您的电话号码进行匹配。

      【讨论】:

      • 这是一个更好的过程,因为这只需要数据库交互。您不必担心数组或循环。
      猜你喜欢
      • 1970-01-01
      • 2021-11-16
      • 2017-12-16
      • 2021-09-12
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多