面试时主要会问 增删改查以及排序和分组
1.查找:
select * from test0709;
select * from test0709 where LAST_NAME like '%Q3%';
select Name,SEX from test0709 where LAST_NAME like 'SQ__VIP';
select * from test0709 where LAST_NAME like 'SQ__VIP';
2.插入:
insert into 表名 (字段名,字段名) values(值,值)
insert into table_name values(值1,值2,...),values(值1,值2,...)
insert into test0709 (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) values ("SQ31","SQ31VIP",18,"F", 200);
insert into test0709 (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) ;
批量新增数据:可以有主键,把主键设置为自增长(1.将id=0;2.将id=null)
3.删除:
delete from table_name where 条件
delete from test0709 where FIRST_NAME="SQ32";
注意安全模式:
SET SQL_SAFE_UPDATES = 0; 表示可以删除数据
4.更新:
update test0709 set LAST_NAME="SQ5555" where FIRST_NAME="SQ01";
5.distinct 删除重复行 as:别名
select distinct 列名 from tbname;
select 列名 as 别名1 from tbname where 条件
6.函数的用法:
select * from test0709 limit 5------查找指定的几行数据
select FIRST_NAME AS "姓",LAST_NAME AS "名" from test0709----查询列别显示为别名
select avg(age) as "平均年龄" from test0709---计算符合条件的平均年龄,且显示为别名
7.连接查询:
SELECT mv_record.movie_id,mv_record.order_id,mv.mvfactory_movie.user_id,mv.mvfactory_movie.team_id FROM `mv_record`JOIN mv.mvfactory_movie ON mv_record.movie_id = mv.mvfactory_movie.team_id where mv_record.movie_id =5701;
1.内连接:
select * from test0709 inner join test0710 on test0709.Name = test0710.Name;
2.外连接:
①.左外连接(左边的数据全部显示,右边没有则显示null)
select * from test0709 left join test0710 on test0709 .Name = test0710.Name;
②.右外连接
select * from test0710 right join test0709 on test0709 .Name = test0710.Name;
8.order by 对数据库的一组数据进行排序
select * from tablename order by id desc/asc;
9、group by 分组
GROUP BY 语句用于结合聚合函数,根据一个或多个列对结果集进行分组。
select customer,sum(price)from orders where a=b group by customer;
聚合函数包括:sum、avg、max、min、count
GROUP BY子句必须出现在WHERE子句之后,ORDER BY子句之前. HAVING语句必须在ORDER BY子句之后。(where先执行,再groupby分组;groupby先分组,having在执行。)
select id,count(*)
from products
where price>=10
group by id
order by id desc
having count(*)>2
10.union、union all(union获取到所有的不同的数据、union all获取到所有的数据)
select id from a
union
select id from b
sql查询举例:
1.根据性别来查询最小的年龄
select sex,min(age) from person group by sex;
2.每个年龄有多少人
select age,count(*) from person group by age
3.年龄小于22的
select * from tbname group by name having age<22
4.查询每个年级的总人数,并按照年级分类
select 年级,count(*) as 年级总数,sum(人数) from tbname group by 年级