zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

挨踢小子MySQL笔记体现SQL功底12道

mysqlSQL笔记 12 体现 小子
2023-06-13 09:17:27 时间

1、复制数据库表数据操作

1、如果是整个表复制表达如下:

insert into table1 select  * from table2

2、如果是有选择性的复制数据表达如下:

insert into table1(column1,column2,column3...) 
select column1,column2,colunm3...from table2

3、一个数据库中的表中的数据复制到另一个数据库中的一个表,使用方法如下:

insert into 数据库A.dbo.table1(col1,col2,col3...) 
select col1,col2,col3... from 数据库B.dbo.table2 
4、直接复制现有表重命名CREATE  TABLE 表名  AS SELECT 语句;

2、sql的子查询可以放到查询字段之中

 select  name,age,(select date from tableB)
from tableA  where age="12";

3、一张表中两个字段值互换(重点思想)

 update table a, table b 
set a.filed1= b.field2, a.field2= b.field1
where a.id = b.id

4、实现数据库两列数据的上下移动操作

 update test set priority=   

(case when id=1  then    

(select priority from test where id=2)    

when id=2 then    

(select priority from test where id=1) end)   

 where id=1 or id=2; 

5、mysql合并字符串

concat(string1,string2,string3,…)

select concat( '1', '01','02')

// 10102  

concat_ws(separator,str1,str2,...)

select concat_ws('-','1','2','3')

// 1-2-3
group_concat()
group_concat( 
[distinct] 要连接的字段 
[order by 排序字段 asc/desc ] 
[separator '分隔符'] 
)
// 例如:
SELECT  group_concat(content  ORDER BY id DESC separator '-') from t_noteinfo  

6、删除重复数据,只保留最小ID编号

delete tablename where id not in(select min(id) from tablename group by name,………………)

7、两张关联表,删除主表中已经在副表中没有的信息

delete from info where not exists 

(select * from infobz where info.infid=infobz.infid)

8、日程安排提前五分钟提醒(日期操作)

select * from 日程安排 

where datediff('minute',f 开始时间,getdate())>5

9、查询出每门课都大于90 分的学生姓名

select name from table group by name having min(fenshu)>90

10、数据结构转换形式

 year   month amount
 1991   1     1.1
 1991   2     1.2
 1991   3     1.3
 1991   4     1.4
 1992   1     2.1
 1992   2     2.2
 1992   3     2.3
 1992   4     2.4

查成这样一个结果

 year m1   m2   m3   m4
 1991 1.1 1.2 1.3 1.4
 1992 2.1 2.2 2.3 2.4

select year, 
    (select amount from   aaa m where month=1   and m.year=aaa.year) as m1,
    (select amount from   aaa m where month=2   and m.year=aaa.year) as m2,
    (select amount from   aaa m where month=3   and m.year=aaa.year) as m3,
    (select amount from   aaa m where month=4   and m.year=aaa.year) as m4
from aaa   group by year

11、find_in_set笔记学习(历史文章有详解,此处略)

SELECT t.dept_id FROM sys_dept t 

WHERE FIND_IN_SET (102,ancestors) 

12、explain查看sql的具体的执行计划(历史文章有详解,此处略)

 explain select * from tablename