行业知识
【SQL实用技巧】-- join系列
2026-11-17 17:07:00
来源:互联网转载
Join系列-Inner,Left,Right
���据准备
()create table all_users( id int comment '用户id', name VARCHAR(20) comment '用户姓名', sex VARCHAR(20) comment '性别', age int comment '年龄') comment '银行用户信息表';insert into all_users values(1,'张三','男',20),(2,'李四','男',29),(3,'王五','男',21),(4,'赵六','女',28),(5,'田七','女',22);select * from all_users;create table black_list( user_id int comment '用户编号', type VARCHAR(20) comment '风控类型')comment '银行黑名单信息表';insert into black_list values(1,'诈骗'),(2,'逾期'),(3,'套现');select * from black_list;
Inner Join
得到两个表的公共部分
查询黑名单用户
-- 写法一select *from all_users ainner join black_list bon a.id=b.user_id;-- 写法二,省略innerselect *from all_users ajoin black_list bon a.id=b.user_id;-- 写法三select *from all_users a ,black_list bwhere a.id=b.user_id;
Left Join
使用Left Join判断是否在黑名单中
select a.*, if(b.user_id is not null, 'YES', 'NO') `黑名单用户`from all_users aleft join black_list bon a.id = b.user_id;
Right Join
上述问题,使用Right Join再做一遍
()select b.*, if(a.user_id is not null, 'YES', 'NO') flagfrom black_list aright join all_users bon a.user_id = b.id;
左连接和右连接区别不大,掌握好Left Join 即可。
上一篇:电梯服务器怎么删除故障码?
下一篇:如何下载苹果设备上的微信应用