sql常用语法
创建表
1.create table [if not exists] 表名(
字段名 类型(长度) [约束],
字段名 类型(长度) [约束],
…
);
2.create table table1 as select* from
插入查询数据
insert into table1 select * from table2
查看当前数据库中的所有表信息
show tables;
查看某张表的表信息
desc 表名;
删除表
drop table 表名:
添加一列
alter table 表名 ADD 列名 类型(长度)
修改一个字段
alter table 表名 change 旧列名 新列名 类型(长度)
删除一列
alter table 表名 drop 列名
修改表名
rename 表名 to 新表名
插入语句
insert into 表名 values(字段1值,字段2值…);
insert into 表名(字段1,字段2,…) values(字段1值,字段2值…);
insert into stu select * from student;
注:将select * from student 的查询机结果追加到stu表内容的后面,而且table关键字是可以省略的。
insert overwrite table stu select * from student;
注:将select * from student 的查询机结果覆盖掉stu表之前的数据,而且table关键字是不可省略的。
插入
insert into stu select * from student
覆盖
insert overwrite table ste select * from student
修改数据
update 表名 SET 列名1=列值1,列名2=列值2,列名3=列值3... WHERE 条件
删除数据
- DELETE FROM 表名 WHERE 条件
保留表结构,只清除数据2. TRUNCATE TABLE 表名
表结构和数据都删除3. drop table 表名
克隆表:
1.CREATE TABLE product_1 LIKE product;
2.CREATE TABLE product_2 AS SELECT * FROM product;
创建外键约束
alter table 从表 add [constraint] [外键名称] foreign key (从表外键字段名) references 主表 (主表的主键);
内连接:
JOIN on
左外连接
LEFT JOIN on
开窗函数
row_number()
创建视图
CREATE VIEW 名字 AS select * from
拼接字符串
concat
①date:MySQL 以 ‘YYYY-MM-DD’ 格式检索与显示date值; 2022-01-01 00:00:00
②datetime:MySQL 以 'YYYY-MM-DD HH:mm:ss’2022-01-01
查看分区:show partitons
表重命名:alter table old_table_name rename to new_table_name;
排序(group by后边 ):ORDER BY
ASC(ascend): 升序(默认)
DESC(descend): 降序
取整函数
round(3.14,2)小数点后
向下取整函数
floor(double a)
向上取整函数
ceil(double a)
取随机数函数(0到1)
:rand()
幂运算函数
pow(2,4) 2的4次幂
绝对值函数
abs()
字符串长度函数
length()
字符串反转函数
reverse()
字符串连接函数
concat( ‘A’, ‘B’)
字符串截取函数
select substr('abcde',3) 返回:cde;
select substr('abcde',3,2) 返回: cd;
字符串转大写函数
upper(),ucase()
字符串转小写函数
lower(),lcase()
去空格函数
trim()
左边去空格函数l
trim()
右边去空格函数
rtrim()
分割字符串函数
select split(‘abtcdtef’,‘t’) 返回:[“ab”,“cd”,“ef”];
获取当前UNIX时间戳函数
unix_timestamp()
UNIX时间戳转日期函数
from_unixtime()
select from_unixtime(1323308943,‘yyyyMMdd’) 返回:20111208;
日期转UNIX时间戳函数
unix_timestamp
指定格式日期转UNIX时间戳函数
select unix_timestamp(‘20111207 13:01:03’,‘yyyyMMdd HH:mm:ss’)
返回:1323234063;
日期时间转日期函数
to_date
行转列
concat(str1,str2,…) --字段或字符串拼接
concat_ws(sep, str1,str2) --以分隔符拼接每个字符串
collect_set(col) --将某字段的值进行去重汇总,产生array类型字段
row_number() over(partition by 分组列 order by 排序列 desc)
替换字符串
REGEXP_REPLACE(a.psn_name,’ ‘,’')