MySQL学习笔记

xiaoxiao2021-02-28  227

本文记录了我在工作中使用的sql语句。

首先搭建环境:

1)安装MySQL数据库;

2)安装Navicat Preminum,是一套数据库管理工具。提供了一个可视化操作界面,可以新建数据库、新建表、导入、导出数据、对表进行增、删、改、查操作。

接下来就是常用的sql语句笔记了。

1 MySql如何把一个表中数据导入到另一个表中?

insert into newtable('a','b') select 'c','d' from table

其中:newtable是新表(待导入数据的表),table是从哪个表导入数据(也就是数据源)。也就是查询table中字段c赋值给新表newtable的字段a,查询新表table的字段d赋值给新表newtable的字段b。

2 如果需要从表b和表c中查询几个字段的值插入到表a中对应的字段。对于这种情况,上面的方式就不适用了,需要使用以下方式: insert into a(field1,field2) select * from(select f1, f2 from b join c) as tb

3 关联更新

需求:同一个数据库有两个表A和B,需要A表与B表通过某个字段关联,用B表中某个字段的值更新A表中某个字段的值。

关联生产例子:

update transfer_person_income_info inner join t_bm_ctincome on transfer_person_income_info.fn =t_bm_ctincome.fnumber set transfer_contract_invoice_info.signcompanyname=t_bm_ctincome.fctcorpnameid 模板格式: update tableA join tableB on tableA.abc = tableB.bcd set tableA.param1 = tableB.param2 注释:更新tableA中的param1字段,在tableA中查询abc属性值等于tableB中属性bcd属性值的记录,将该记录的param2字段赋值给tableA的param1字段。 3.1 一个表字段更新 需求描述:将表person_info中名字是zhangsan,lisi的人的中文名chinesename赋值给fullname全名。 update person_info  set fullname= chinesename where name in('zhangsan','lisi') 4 清空全部数据 delete from B 删除表B,支持回滚操作,所以比较truncate来说慢一些。 truncate table  A 删除表A,删除表A中内容 5 查询 5.1 mysql三表联合查询,用inner join on模板写 模板例子如下: select  *  from table1 inner join table2 on table1.field1 = table2.field1 inner join table3 on table1.field1 = table3.field1 5.2 查询某个子段的的最大值和最小值 select min(id), max(id) from t_ar_other_16  查询表t_ar_other_16 中字段id的最小值和最大值 5.3 按条件查询数量 select  count(1)  from  t_ar_other_16WHERE  fcreatetime <'2017-05-09' 查询表t_ar_other_16 表中创建时间<2017-05-09的记录数 5.4 查询表bic_t_test (A)关联bic_ctincome(B) 查询A中fanumber与B表中fbnumber相同并且B表fid不为null,A表fanumber不为null且不为空的记录总数。 select  DISTINCT COUNT(1) from bic_t_test A left join bic_ctincome B  on A.fanumber= B.fbnumber where B.fid is not null and A.fanumber is not null and A.fanumber<>'' 说明:select DISTINCT 在select之后加上DISTINCT可以避免重复查询 5.5 查询一个表tableB中某些字段值,并新建一个表tableA,将查询结果插入新表中。 实例代码如下: create tableA('a','b') select 'a','b' from tableB 查询tableB表的'a'和'b'字段,创建新表tableA,并赋值给tableA表中 ‘a’,‘b’字段。 表创建语句可以通过mysql中创建表的sql语句,运行此条命令来执行创建表。 待以后扩充---

转载请注明原文地址: https://www.6miu.com/read-23028.html

最新回复(0)