一、插入数据
1.1 插入完整数据
insert into table_name values (value1, value2, ... valuen)
insert into table_name (column1, column2, ...columnn) values (value1, value2,... valuen)
1.2 插入指定数据
insert into table_name (column1, column2, ...columnn) values (value1, value2,... valuen)
1.3 一次性插入多条数据
插入所有字段数据:
insert ino table_name
values
(value1, value2, ... valuen),
(value1, value2, ... valuen),
(value1, value2, ... valuen)
指定字段插入:
insert ino table_name
(column1, column2, ... columnn)
values
(value1, value2, ... valuen),
(value1, value2, ... valuen),
(value1, value2, ... valuen)
1.4 将查询结果插入
insert into target_table
(tar_column1, tar_column2 ..., tar_columnn)
(select src_column1, src_column2 ... , src_columnn
from source_table
[where condition])
二、更新数据
update table_name
set column1 = value1, column2 = value2, ... , columnn = valuen
[where condition]
三、删除数据
delete from table_name [where condition]
四、查询数据
4.1 查询所有数据
select * from table_name [where condition]
select column1, column2, ... , columnn from table_name [where condition]
4.2 条件从句
< > <>: 小于、大于、不等于
in、not in:属于/不属于某个给定值之间
between and:属于某个值范围
like: 模糊匹配,通常配合”%”、“_”一起使用
is null、is not null: 字段是否为空
and:同时满足条件
or:满足一个条件即可
order by: 排序条件(搜索结果需要有这个字段)
group by:对结果进行分组处理
having:对group by语句进行限制
with rollup:对group by语句使用,显示本次查询出的所有记录的综合信息
limit [m],n: m表示从哪一行开始返回,n表示返回的行数
regexp:使用正则匹配
4.3 聚合查询
4.3.1 查询数据的总行数,count()函数
select count(*)/count(0) from table_name
select count(column) from table_name
4.3.2 查询某列数据的综合 ,sum()函数
select sum(column) from table_name
//查询每个类别下的商品总价格
select t_category_id, sum(t_price) from t_goods group by t_category_id
4.3.3 查询某列数据最小值,min()函数
select min(t_price) from t_goods
//查询每个类别下最小价格
select t_category_id, min(t_price) from t_goods group by t_category_id
PS: max()函数,avg()函数同理
4.4 JOIN语句
4.4.1 inner join
返回连接条件相匹配的多个表数据,只有数据均有值时才返回,如果有为null的列,不返回
4.4.2 left join
左连接, 返回符合记录的记录,如果右表没有对应的行,右表的字段返回null
PS: right join, cross join 同理
4.5 子查询语句
一般包括any、some、all、exists、not exists、in 和 not in,使用示例:
SELECT id, t_category_id, t_category, t_name, t_price
FROM t_goods
WHERE t_category_id > ANY (SELECT id FROM t_goods_category);
any、some、all、exists、not exists、in 和 not in 是满足条件的行为词,如上使用的any,只需满足大于任意的id即满足条件,其他同理
4.6 UNION联合语句
union 和 union all 的区别,union会去除重复的记录,union all 的执行效率更高
语法如下:
select col1, col2, ... , coln from table1
union [all]
select col1, col2, ... , coln from table2