数据库操作:SQL常用查询
在数据操作中,绝大部分都是查询数据,SQL语言体系也是以查询为主。
除了简单查询全表数据外,SQL还提供了很多查询功能。
where条件查询
用于提取那些满足指定标准的记录。
语法:
select 查询列 from 表名 where 条件;
select * from stu where name="张三";
select * from stu where age>12;
模糊查询
我们使用like关键词进行模糊查询。用于条件查询中。
语法:
select * from stu where name like '%李%'
注:%为通配符,表示任意字符
select * from stu where name like '王%';
select * from stu where name address '%金龙盛世%';
分组查询
分组是将查询结果按照指定字段进行分组,字段值相同的为一组。
语法:
selrct * from stu
group by 属性名 [with rollup]
集合函数:
group by关键字通常与集合函数一起使用。集合函数包括count()函数、sum()函数、avg()函数、max()函数和min()函数等。
count()函数:用于统计记录的条数。
sum()函数:用于计算字段的值的总和。
avg()函数:用于计算字段的值的平均值。
max()函数:用于查询字段的最大值。
min()函数:用于查询字段的最小值。
连接查询
(准备两个表 stu和class )
连接查询是将多张表中的关联数据一起显示。使用 join 可以在两个或多个表中查询数据。
你可以在 select, update 和 delete 语句中使用join 来联合多表查询。
inner join(内连接,或等值连接):获取两个表中字段匹配关系的记录。
select * from
stu inner join class
on stu.classid=class.id;
left join(左外连接):获取左表所有记录,即使右表没有对应匹配的记录。
select * from
stu left join class
on stu.classid=class.id;
right join(右外连接): 与 left join 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
select * from
stu right join class
on stu.classid=class.id;