gpt4 book ai didi

mysql - 使用子字符串条件连接表

转载 作者:行者123 更新时间:2023-11-30 23:18:17 25 4
gpt4 key购买 nike

我有两个表:

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 说:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'int) where tblpeserta.id is null

有没有更好的查询来解决我的问题?!​​

最佳答案

尝试

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 *
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

关于mysql - 使用子字符串条件连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16630466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com