1.数据库表的增删改查操作
1.1添加操作:
1.insert[into] tb_name[col_name,...] values(val,...)
2.insert tb_name values(值1,值2,....)
# 指定所要插入数据的列:
3.insert into tb_name (列1, 列2,...) VALUES (值1, 值2,....)
# 查询tb_name表中age大于30的username添加到tb_name1中
4.insert tb_name1 select username from tb_name where age>=30;
1.2 删除操作:
1.delete from tb_name where 列名称 = 值
# 可以在不删除表的情况下删除所有的行的信息。这意味着表的结构、属性和索引都是完整的:
2.delete from table_name / DELETE * FROM table_name
1.3更新操作:
1.update tb_name set 列名称 = 新值,.... where 条件(列名称 = 某值)
#示例:
#我们为 lastname 是 "Wilson" 的人添加 firstname:
2.UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson'
1.4查询操作:
1.select * from tb_name -- 查询tb_name中的多有信息
2.select *|[column_name(s)] into new_table_name [IN externaldatabase] from old_tablename
-- 从一个表中选取数据,然后把数据插入另一个表中。
3.select distinct 列名称 from 表名称 -- 在表中找到不同的字段
4.select [ALL|DISTINCT]
{*|tb_name.*|[tb_name.field1[as alias1]][,tb_name.field2[as alias2]][....]}
[left | right | inner join tb_name] -- 联合查询,内连接外连接
[where ....] -- 指定结果需满足的条件
[group by..] -- where过滤后的结果按照哪个字段分组 如:group by age 通过age进行分组,相同age分在一组
[having....] -- 对已经分组的数据进行过滤的条件
[order by..] -- 指定查询记录按一个或多个条件排序 降序DESC 升序ASC
[limit {[offset,] row_count | row_countOFFSET offset}];
-- limit a,b a从第几个数开始返回(不包括a),b返回多少个数,分页
注意:[] 代表可选,{}代表必选
1.5关键字执行顺序:
from -> where -> group by -> having -> select -> order by
2.子查询
1.查询tb_user表中的金额字段对应的值的平均数
1000=select AVG(tb_price) from tb_user;
select tb_id,tb_name,tb_price from tb_user where tb_price >1000
等价:
select tb_id,tb_name,tb_price from tb_user where tb_price >(select AVG(tb_price) from tb_user);这就是子查询; 如果结果为多个值,那么>可以在后面加上any、some、all
2.[NOT] IN与!=ALL、< >ALL等效, = ANY与 in等效