【代码总结】SQL语句设计

1、根据空值(NULL)检索条件

 1 select * from user where age is not null; //查询年龄为null的所有用户 

2、使用IN进行范围对比查询

1 select * from user where id in ('1','3','5');        //查询用户id为1,3,5的所有用户
2 select * from user where id not in ('1','3','5');    //查询用户id不是1,3,5的所有用户

3、使用 BETWEEN AND 进行范围比较查询

1 select * from user where id between 1 and 4;        //查询id在1和4之间的所有用户
2 select * from user where id not between 1 and 4;    //查询id不在1和4之间的所有用户

4、使用LIKE进行模糊匹配

  百分号"%":表示0个或任意多个字符

  下划线"_" :表示单个的任意一个字符

1 select * from user where username like 'li%';    //查询所有姓li的用户
2 select * from user where username like '七_年%';  //查询查询七某年

5、使用ORDER BY 对查询结果排序

1 select * from user order by id asc;    //按id进行升序排序
2 select * from user order by id;        //按id进行升序排序
3 select * from user order by id desc;   //按id进行降序排序

6、使用LIMIT限定结果行数

1 select * from user limit 5;      //查询前5个用户
2 select * from user limit 0,5;    //查询前5个用户

7、使用统计函数

1 select count(*) from user;      //统计表中的记录数

8、使用GROUP BY对查询结果分组

1 select age,count(*) from user group by age;   //统计用户表中每个年龄段有多少人
2 select age,count(*) from user group by age having count(*) > 1;   //要求总人数大于1的,having对分组后的结果进行筛选
3 select age,count(*) c from user group by age having c > 1;        //要求总人数大于1的,having对分组后的结果进行筛选
原文地址:https://www.cnblogs.com/sqyysec/p/6784133.html