select条件查询

2020-10-30  本文已影响0人  爱折腾的傻小子
条件查询
select * from test1 where b = 'abc';
select * from test1 where a<>1;
select * from test1 where a!=1;
-- sql语句中尽量使用<>来做不等判断
-- 数值按照大小比较
select * from test1 where a>1;
-- 字符按照ASCII码对应的值进行比较,比较时按照字符对应的位置一个字符一个
字符的⽐较
select * from test1 where b>'a';
select * from test1 where b>'ac';
逻辑运算符
/*
mysql> select * from test3;
+---+---+
| a | b |
+---+---+
| 1 | a |
| 2 | b |
| 2 | c |
| 3 | c |
+---+---+
4 rows in set (0.00 sec)
*/
select * from test3 t where t.a=2 and t.b='c';
/*
+---+---+
| a | b |
+---+---+
| 2 | c |
+---+---+
1 row in set (0.00 sec)
*/
select * from test3 t where t.a=1 or t.b='c';
select * from stu a where a.name like '张%';
select * from stu a where a.name like '%学%';
select * from stu a where a.name like '张_';
select * from stu t where t.age between 25 and 32;
/*
+----+-----+-----------+
| id | age | name |
+----+-----+-----------+
| 2 | 25 | 李四 |
| 3 | 26 | 张学友 |
| 4 | 32 | 刘德华 |
+----+-----+-----------+
3 rows in set (0.00 sec)
*/
select * from stu t where t.age >= 25 and t.age <= 32;
select * from test6 t where t.age in (10,15,20,30);
/*
+------+------+
| id | age |
+------+------+
| 2 | 15 |
| 4 | 20 |
| 6 | 10 |
| 7 | 10 |
| 8 | 30 |
+------+------+
5 rows in set (0.00 sec)
*/
select * from test6 t where t.age not in (10,15,20,30);
/*
+------+------+
| id | age |
+------+------+
| 1 | 14 |
| 3 | 18 |
| 5 | 28 |
+------+------+
3 rows in set (0.00 sec)
*/
select * from test7 t where t.a is null;
/*
+------+------+
| a | b |
+------+------+
| NULL | b |
| NULL | NULL |
+------+------+
2 rows in set (0.00 sec)
*/
select * from test7 t where t.a is null or t.b is null;
/*
+------+------+
| a | b |
+------+------+
| NULL | b |
| 3 | NULL |
| NULL | NULL |
+------+------+
3 rows in set (0.00 sec)
*/
select * from test7 t where t.a is not null;
/*
+------+------+
| a | b |
+------+------+
| 1 | a |
| 3 | NULL |
| 4 | c |
+------+------+
3 rows in set (0.00 sec)
*/
select * from test7 t where t.a is not null and t.b is not
null;
/*
+------+------+
| a | b |
+------+------+
| 1 | a |
| 4 | c |
+------+------+
2 rows in set (0.00 sec)
*/
/*
mysql> select * from test8;
+------+------+
| a | b |
+------+------+
| 1 | a |
| NULL | b |
| 3 | NULL |
| NULL | NULL |
| 4 | c |
+------+------+
5 rows in set (0.00 sec)
*/
select * from test8 t where t.a<=>null;
/*
+------+------+
| a | b |
+------+------+
| NULL | b |
| NULL | NULL |
+------+------+
2 rows in set (0.00 sec)
*/
select * from test8 t where t.a<=>null;
/*
+------+------+
| a | b |
+------+------+
| NULL | b |
| NULL | NULL |
+------+------+
2 rows in set (0.00 sec)
*/
select * from test8 t where t.a<=>1;
/*
+------+------+
| a | b |
+------+------+
| 1 | a |
+------+------+
1 row in set (0.00 sec)
*/
经典面试题
-- 下面的2个sql查询结果一样么?
select * from students;
select * from students where name like '%';
-- 
-- 当name没有NULL值时,返回的结果一样。
-- 当name有NULL值时,第2个sql查询不出name为NULL的记录
总结
上一篇 下一篇

猜你喜欢

热点阅读