sql语句(三)

一、分组查询
1、group by
❤对products表,根据vend_id分组,统计每个vend_id下面总记录数
select vend_id, count(*) from products group by vend_id;
2、where>group by >order by
3、having——过滤分组
        where过滤指定的行, having过滤指定的分组
❤根据cust_id分组,统计每个cust_id总记录数,总记录个数>=2
select  cust_id,count(*) from orders group by cust_id having count(*)>=2;
❤对products表,在prod_price>=10,根据vend_id分组,统计每个总数>=2
select  vend_id,count(*) from products where prod_price>=10
group by vend_id having count(*)>=2;
4、注意!select只能查看group by字句后有的列和集合计算的列
                group by后面可以加多个列,分组的顺序跟字段的顺序相同
5、字句顺序: select>from> where> group by> having> order by> limit 
二、子查询
❤查询safe产品对应的vend_name
select vend_id from products where prod_name='Safe';
select vend_name from vendors where vend_id='1003';
select vend_name from vendors where vend_id=(select vend_id from products where prod_name='Safe');

三、 插入数据:——insert
1、插入完整的行
insert into 表名(列名) values (各个列的值)
2、插入行的一部分
3、插入多行
4、插入某些查询的结果
insert into 表A(列1,列2)select 列1,列2 from 表B;
5、快捷键:执行选中的部分——Ctrl+shift+enter
6、表结构与数据结果
desc  products;#查询products表结构
前四个字段必须有值,最后字段可为空
❤往products表中添加一条数据——插入完整行
insert into products(prod_id,vend_id,prod_name,prod_price,prod_desc)
values('pro01',1001,'prod_001',15.09,'prod_desc');
注意!!!vend_id是外键,是products表中的数据(1001),不能是其他数据
desc products;
select * from products;
❤往customers表中插入一条数据——插入行的一部分
只需要插入cust_id,cust_name两个字段,值分别为‘10010’,‘cust001’
insert into customers(cust_id,cust_name)values('10010','cust001');
❤往customers表中插入3条数据——插入多行
cust_id,cust_name分别是(10010,cust001)(10011,cust002)……
insert into customers(cust_id,cust_name)values(10013,'cust001'),(10011,'cust002'),(10012,'cust003');
❤向customers表中插入数据——插入其他查询得到的数据
其中cust_id,cust_name来自vendors表中vend_id 为1006的vend_id和vend_country的值
insert into customers(cust_id,cust_name) select vend_id,vend_country from vendors;
四、 更新数据——update
update 表名 set 列名=值 where 条件   #不添加where条件,修改所有信息,慎用!!!
❤修改customers表中cust_id为10005的cust_email为123@qq.com
update customers set cust_email='123@qq.com' where cust_id='10005';
五、删除数据——delect——一定要加where
1、从表中删除特定的行——加where
2、删除所有行——加where—— where 1=1
❤删除customers表中cust_id为‘10011’的数据
delete from  customers where cust_id='10011';
#注意,如果该条数据被其他表引用,则不能删除
3、delect语句删除表中数据,而不是表本身
4、truncate 删除整张表,再创建一个空表,速度特别快 truncate table 表名

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值