一、分组查询
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总记录数,总记录个数>=2select cust_id,count(*) from orders group by cust_id having count(*)>=2;
❤对products表,在prod_price>=10,根据vend_id分组,统计每个总数>=2select vend_id,count(*) from products where prod_price>=10group by vend_id having count(*)>=2;
4、注意!select只能查看group by字句后有的列和集合计算的列
group by后面可以加多个列,分组的顺序跟字段的顺序相同
5、字句顺序:
select>from> where> group by> having> order by> limit
二、子查询
❤查询safe产品对应的vend_nameselect 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.comupdate 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 表名