这里都用str_1代表字段、表达式、特征值,用table_1代表表。
MySQL基于
文章目录
基础查询
查询表中单个字段
select str_name from table_1;
查询表中多个字段
select str_name1,str_name2 from table_1;
查询表中全部字段
select * from table_1;
查询常量值
select 100;
select 'str';
查询表达式
select 100%3;
条件查询
- 条件查询即在基础的查询中添加where 语句。
select str_1 from table_1 where condition_1;
筛选条件方式
简单运算符
- =
- <,>
- != , <>
- <= , >=
逻辑运算符
- not
- or
- and
模糊查询
- like
- between and
- in
- is null
通配符
- % 任意多个字符,包括0字符
- _ 任意单个字符
- 可自行设置,后接ESCAPE即可
条件查询示例
算术运算符示例
SELECT
CONCAT(first_name,last_name) AS employee_name,
department_id
FROM
employees
WHERE
department_id<>90;
逻辑运算符示例
SELECT
*
FROM
employees
WHERE
NOT(department_id>=90 AND department_id<=110) OR salary>15000;
模糊查询示例
#案例1:查询员工名中包含字符a的员工信息
select
*
from
employees
where
last_name like '%a%';
#案例2:查询员工名中第三个字符为n,第五个字符为a的员工名和工资
select
last_name,
salary
FROM
employees
WHERE
last_name LIKE '__n_a%';
#案例3:查询员工名中第二个字符为_的员工名
SELECT
last_name
FROM
employees
WHERE
last_name LIKE '_$_%' ESCAPE '$';
SELECT
*
FROM
employees
WHERE
employee_id BETWEEN 90 AND 100;
SELECT
last_name,
job_id
FROM
employees
WHERE
job_id IN( 'IT_PROT' ,'AD_VP','AD_PRES');
select *
from table_1
where str_1 is null;
select *
from table_1
where str_1 is not null;
排序查询
- order by 语句
- 升序 asc;降序 desc
select *
from table_1
where str_1 is null
order by str_2 asc;
定义新名字
- 可以对表中的值或表达式定义新名字,从而拥有新列
- 或防止重名出现,以便区分
- 可以用 as 也可以用空格代替
- 但需要注意,如果定义的新名字是含空格的,则需要放在引号中,否则引发报错
select str_1 as xx;
select str_1 xx;
select str_1 as 'x x';
select str_1 'x x';
去重
- 如果想查看某一特征的种类一共有多少种
select distinct str_1 from table_1;
拼接
- Sql中 +号 只代表运算符,如果想要拼接字段,则需要使用CONCAT()
select concat('a','b','c') as result;
注释
- 当对某一特征值操作时,可能存在该列特征值中含有空值,此时若使用表达式则会报错。
- ifnull(str_1,0) :则若为null则赋值为0,否则就是str
select * from table_1
order by 12*ifnull(str_2,0) desc;