Mysql-不同场景下操作/查询数据库表
1. 通过关联字段把一张表的字段值更新另一张表的字段值
update table_a a, table_b b set a.username = b.username where a.id = b.id; -- 以下2种更新结果以table_b的查询结果为准,table_b中没有查到的记录会全部被更新为null,相当于外连接 update table_a a set username = (select name from table_b where id = a.id); update table_a a left join table_b b on a.id= b.id set a.username = b.name;
2. 将查询结果插入另一张表
-- insert into 表1(列名) select 列名 from 表2;
insert into table_a(username) select name from table_b where id=1;
3. with tab as...
属于子查询的一种解决方案---公用表表达式(CTE), 使用该语法必须注意:
-- 1. CTE后面必须直接跟使用CTE的SQL语句(如select、insert、update等), 否则, CTE将失效. with
tab as ( select user_code from table_a where user_code like '%ad%' ) select * from table_b where user_code in (select * from tab) -- 2. CTE后面也可以跟其他的CTE, 但只能使用一个with, 多个CTE中间用逗号(,)分隔. with tab1 as( select * from table_a where name like '赵%' ), tab2 as( select * from table_b where age> 20 ), tab3 as( select * from table_c where gender = 0 ) select a.* from tab1 a, tab2 b, tab3 c where a.id = b.id and a.id = c.id
4. 待更新
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库