• 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可是会使系统整体出现问题的。
  • 相关阅读:
    poj 2312 Battle City
    poj 2002 Squares
    poj 3641 Pseudoprime numbers
    poj 3580 SuperMemo
    poj 3281 Dining
    poj 3259 Wormholes
    poj 3080 Blue Jeans
    poj 3070 Fibonacci
    poj 2887 Big String
    poj 2631 Roads in the North
  • 原文地址:https://www.cnblogs.com/l10n/p/12606814.html
Copyright © 2020-2023  润新知