如何检查Integer数组中哪些记录不存在于mysql中

时间:2016-09-26 07:13:13

标签: mysql

REPORTER      PARTNER  NET_WEIGHT  YEAR     COMMODITY

'Egypt',     'Canada',      '5',   '2010',   'wheat'
'Germany',     'UK',        '1',   '2011',   'wheat'
'Mexico',    'France',       '5',  '2011',   'wheat'

这是我的表我想创建一个我们想要获取数据的程序,这些数据在NET_WEIGHT不存在的表中不存在

当我将输入作为“1,12,16”

传递时,我想要这样

然后它应该返回12 | null和16 | null我必须检查表中没有找到NET_WEIGHT,因此我们应该得到NET_WEIGHT | null数据请建议我如何做到这一点

2 个答案:

答案 0 :(得分:1)

drop procedure if exists `tokensise`;
delimiter //
CREATE DEFINER=`root`@`localhost` procedure `tokensise`(`instring` varchar(255))
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
begin
declare   tempstring varchar(100);
declare   outstring  varchar(100);
declare  checkit int;
set tempstring = ltrim(rtrim(instring));
set checkit = 0;
drop table if exists occursresults;
create table occursresults(letter char(1), occurs int);
looper: while   tempstring is not null and instr(tempstring,',') > 0 do
        set outstring = substr(tempstring,1,instr(tempstring, ','));
        set tempstring = ltrim(rtrim(replace(tempstring,outstring,'')));
        set outstring = replace(outstring,',','');
        set checkit = checkit + 1;
        insert into occursresults
        select  outstring, t.NET_WEIGHT
                   from (select outstring os) d left join t on  t.NET_WEIGHT = d.os;
end while; 
    set outstring = tempstring; 
    set tempstring = ltrim(rtrim(replace(tempstring,outstring,'')));
    set outstring = replace(outstring,',','');
    set checkit = checkit + 1;
    insert into occursresults
        select  outstring, t.NET_WEIGHT
                   from (select outstring os) d left join t on  t.NET_WEIGHT = d.os;

end //
delimiter ;

结果

MariaDB [sandbox]> call tokensise('1,2,5');
Query OK, 2 rows affected (0.38 sec)

MariaDB [sandbox]> select * from occursresults;
+--------+--------+
| letter | occurs |
+--------+--------+
| 1      |      1 |
| 2      |   NULL |
| 5      |      5 |
| 5      |      5 |
+--------+--------+
4 rows in set (0.00 sec)

答案 1 :(得分:0)

我会使用2个表并相互比较 - 我也使用NOT IN而不是NOT EXIST - 我在足球数据库上使用的这个sql检查队列中是否存在团队而不是stats表。下面的代码将显示hometeam不存在team.stats的结果中的所有行。

SELECT  *
FROM    results
WHERE   hometeam NOT IN (SELECT team FROM stats)