SQL 语句的添加、删除、修改
添加、删除、修改使用 db.Execute(Sql)命令执行操作
(一) Select 语句
- 普通查询
- 查询全部的行和列
select * from users
- 查询部分的行并用 as 命名列(as 可用空格代替)
select UserName as 用户名,NickName 密码,sex from users where sex = 0 select UserName,NickName,sex from users where sex <> 0
- 查询空行
- select UserName from users where sex is null;
- select UserName from users where sex = "";
- 使用常量列
select UserName as 用户名,"中北大学" as "学校" from users;
- 限制固定行数
select UserId ,UserName as 用户名 from users limit 2,4;
- 升序排列 降序排列 按照多列排序
- select * from users where Height >178 order by age asc;
- select * from users where Height >178 order by age desc;
- select UserName as 用户名,Height 身高,Age as 年龄 from users where Age>20 order by Height asc, Age desc;
- 随机查询前 20 条数据
Select * from users order by rand () limit 20;
- 关键字顺序:
Where------group by-----having order by
- 高级查询:
- 模糊查询——like
select SName as 姓名 from Students where Sname like ‘张%’;
- 模糊查询——IS NULL
select Sname as 姓名,SAddress as 地址 form Students where SAddress is null
- 模糊查询——between
select StudentId,Score from Score where Score between 60 and 80
- 模糊查询——in
select Sname as 学员姓名,SAddress as 地址 from Students where SAddress in(‘北京’,’广州’,’上海’);
- 聚合函数
- 分组查询
分组查询——GROUP BY
分组查询——多列分组
分组查询——HAVING
-
- 分组查询总结
- where 字句从数据源中去掉不符合其搜索条件的数据
- group by 字句搜集数据航到各个组中
- 统计函数为各个组计算统计值
- having 字句去掉不符合其搜索条件的各组数据行
- 使用 group by 时,select 后面出现的内容要么为聚合函数, 要么为 group by 后面出现的内容
- 关键字的先后顺序:where——group by——having——order by
- 分组查询总结
多表连接查询
分类:
内连接(inner join):(等值连接、内连接)只返回两个表中连结字段相等的行外连接:
- 左外连接(left join)返回包括左表中的所有记录和右表中连结字段相等的记录
- 右连接(right join):返回包括右表中的所有记录和左表中连结字段相等的记录。