使用子字符串条件连接表

时间:2013-05-19 00:56:32

标签: mysql join substring outer-join

我有两张桌子:

create table t1(
id int unsigned not null auto_increment,
group varchar(3) not null,
number int unsigned zerofill,
used enum('YES','NO') default );

id   group   number  used
1    '110'   00001   'YES'
2    '110'   00002   'YES'
3    '110'   00003   'YES'
4    '210'   00001   'YES'
5    '210'   00002   'YES'
6    '210'   00003   'YES'
7    '310'   00001   'YES'

create table t2(
id int unsigned not null auto_increment,
number varchar(13) default null);

id   number  
1    '110-00001'
2    '110-00002'
3    '210-00002'
4    '310-00001'

我的第一个目标是找到t1中未在t2中使用的每条记录:

查询结果:

id   group   number  used
3    '110'   00003   'YES'
4    '210'   00001   'YES'
6    '210'   00003   'YES'

我的第二个目标是将列设置为“否”:

id   group   number  used
3    '110'   00003   'NO'
4    '210'   00001   'NO'
6    '210'   00003   'NO'

我试过使用这样的查询:

  select * from t1 
left outer join t2 
             on t1.number = cast(substring(t2.number,8,5) as int) 
          where t2.id is null;

但mySQL说:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   在'int)附近,其中tblpeserta.id为null

对我的问题有更好的查询吗?!

1 个答案:

答案 0 :(得分:0)

尝试

UPDATE t1 LEFT JOIN t2
    ON t1.`group` = LEFT(t2.number, 3)
   AND t1.number = 0 + RIGHT(t2.number, 5)
   SET t1.used = 'NO'
 WHERE t2.id IS NULL

和SELECT

SELECT *
  FROM t1 LEFT JOIN t2
    ON t1.`group` = LEFT(t2.number, 3)
   AND t1.number = 0 + RIGHT(t2.number, 5)
 WHERE t2.id IS NULL

输出:

| ID | GROUP | NUMBER | USED |
------------------------------
|  3 |   110 |      3 |   NO |
|  4 |   210 |      1 |   NO |
|  6 |   210 |      3 |   NO |

<强> SQLFiddle