mysql进行inner join on查询,关联字段因为字段类型不同导致查询结果有误。


mysql进行inner join on查询,关联字段因为字段类型不同导致查询结果有误。
create table `goods`(
`id` int(11) not null,
`name` varchar(255) default null,
`type` int(1) default null,
PRIMARY KEY (`id`),
KEY idx_type(`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
create table `orange`(
`id` int(11) not null,
`name` varchar(255) default null,
`goods_type` varchar(255) default null,
PRIMARY KEY (`id`),
KEY idx_goods_type(`goods_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
insert into goods select 1,'橘子',1;
insert into goods select 2,'苹果',2;
insert into goods select 3,'柿子',3;
insert into goods select 4,'桃子',4;
insert into goods select 5,'香蕉',5;
 
insert into orange select 1,'丑橘','1aaaa';
insert into orange select 2,'砂糖橘','2bbbb';
insert into orange select 3,'蜜桔','1';
insert into orange select 4,'长兴岛桔','4dddd';
 

 

 

当执行SQL:
select g.name as goods_name ,o.goods_type,o.name
from goods g inner join orange o on g.id = o.goods_type
where g.type = 1;
返回的结果如下:

 

 

其中 goods_type 为 1aaaa 并不是我们想要的数据,所以上面的SQL是错误的,应该把SQL改为:
select g.name as goods_name ,o.goods_type,o.name
from goods g inner join orange o on cast(g.id as char)    = cast(o.goods_type as char)   
where g.type = 1;
 
做表关联的时候,关联字段一定要是相同字段,因为如果做大数据量连表查询的时候,本就因为连表导致的查询效率降低,如果字段类型不同,同时还会导致mysql会不停的进行转换类型比较,这样的话,可能会导致查询效率降低,无限堆积的慢查询sql可是会使系统整体出现问题的。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM