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