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. 待更新

 

posted @   静沐丶暖阳  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示