1.语法格式
条件查询:
select
(字段1,字段2,字段3......)
from
(表名)
where
条件1 and/or 条件2.......;
模糊查询:
select
(字段1,字段2,字段3......)
from
(表名)
where
条件1 (列名 like '');
(其中%表示多个字符,_表示一个字符);
例:
mysql> select *from emp where ename like'S%';
+-------+-------+---------+------+------------+---------+------+--------+
| EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO |
+-------+-------+---------+------+------------+---------+------+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7788 | SCOTT | ANALYST | 7566 | 1987-04-19 | 3000.00 | NULL | 20 |
+-------+-------+---------+------+------------+---------+------+--------+
2 rows in set (0.00 sec)注意若想表示_,应该加入转义符号'\'
mysql> select *from emp where ename like'\_%';
2.符号
基本条件 | < > = |
不等于 | <> or != |
介于两个值之间(第一种方式) | 列名>= num1 and 列名 <=num2; |
介于两个值之间(第二种方式) | 列名 between num1 and num2; (num1必须<num2) |
查询NULL | is null ; |
查询不为NULL | is not null; |
条件连接词 | 条件1 and 条件2 (两个条件同时满足); |
条件1 or 条件2 (多个条件满足一个即可) | |
列名 in( , .......); (注意 in 是集合不是区间 列名 in(100,500)!=列名 between 100 and 500) | |
列名 not in( , .......); |
3.注意点
- 在数据库中NULL(代表什么也没有,他不是一个值) 不可以用等号进行衡量,需要用“is NULL”
mysql> select ename ,sal from emp where comm is null;
+--------+---------+
| ename | sal |
+--------+---------+
| SMITH | 800.00 |
| JONES | 2975.00 |
| BLAKE | 2850.00 |
| CLARK | 2450.00 |
| SCOTT | 3000.00 |
| KING | 5000.00 |
| ADAMS | 1100.00 |
| JAMES | 950.00 |
| FORD | 3000.00 |
| MILLER | 1300.00 |
+--------+---------+
10 rows in set (0.00 sec)
2.注意:and优先级>or 的优先级;所以加括号(若or 先执行)
mysql> select * from emp where sal>2500 and(deptno=10 or deptno=20);
+-------+-------+-----------+------+------------+---------+------+--------+
| EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO |
+-------+-------+-----------+------+------------+---------+------+--------+
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7788 | SCOTT | ANALYST | 7566 | 1987-04-19 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 |
+-------+-------+-----------+------+------------+---------+------+--------+
4 rows in set (0.00 sec)