Home > Backend Development > PHP Tutorial > 两张百万级的数据表,联合查询的有关问题

两张百万级的数据表,联合查询的有关问题

WBOY
Release: 2016-06-13 10:09:20
Original
918 people have browsed it

两张百万级的数据表,联合查询的问题
两张数据表A,B。
A、B表有两个字段:EXP_CODE   ,CODE;
现要找出A、B表中EXP_CODE字段等于 'R8_002_XZ,和EXP_CODE不相同的记录,用下面的语句,如果两表EXP_CODE记录上万的情况下,基本上就死机了,何况到百万级。请问如何改进。

select   *   from   a   where   EXP_CODE= 'R8_002_XZ '   and   code   not   in   (select   code   from   b)


------解决方案--------------------
select * from a where EXP_CODE= 'R8_002_XZ ' and code not in (select code from b)

=======================================================

select * from a left join b on a.code=b.code
where a.EXP_CODE= 'R8_002_XZ ' and b.code is null

再看你的code上有无索引,如无,建索引, exp_code 上也建


------解决方案--------------------
楼上正解,但是对于百万条记录数据库还是慢的,可以用limit限定
------解决方案--------------------
select * from a where exp_code= 'r8_002_xz ' and code not exist(select code from b where exp_code!= 'r8_002_xz ')
上面的语法可能有点问题,但是逻辑关系应该是对的.
要求:version> 4.1,支持子查询.
------解决方案--------------------
这个是你要的吗
select * from a left join b on a.code=b.code and a.EXP_CODE=b.EXP_CODE
where a.EXP_CODE= 'R8_002 ' and b.code is null


------解决方案--------------------
嵌套的select效率比较低,尽量用inner join, left join代替
------解决方案--------------------
上面写错了.改成以下:
select * from a where exp_code= 'r8_002_xz ' and code not in(select code from b where exp_code!= 'r8_002_xz ');
或者
select * from a where exp_code= 'r8_002_xz ' and not exists(select code from b where exp_code!= 'r8_002_xz ' and a.code=b.code);



------解决方案--------------------
select * from a left join b on a.code=b.code and a.EXP_CODE=b.EXP_CODE and b.code is null

你只需要找出a中有而b中没有的记录,然后按b的结构追加就可以了!

辛苦了, "农普 "同行!

------解决方案--------------------
哈哈哈.... 遇着了.....

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template