数据库基本概念
- 名词解释:
- DB : 数据库(Database),存储数据的仓库,保存一系列有组织的数据。
- DBMS:数据库管理系统(Database Management System)。数据库是通过DBMS创建和操作的容器。
- SQL:结构化查询语言(Structure Query Language),专门用来对数据库进行操作的语言。
- DML:数据操纵语句(Data Manipulation Language),用于添加、删除、修改、查询数据库记录并检查数据完整性。
eg:
insert
,update
,delete
,select
- DDL:数据定义语句(Data Definition Language),用于数据库、表的创建、修改和删除。
eg:``create table
,alert table
,drop table
,create index
,drop index
- DCL:数据控制语句(Data Control Language),用于定义用户的访问权限和安全级别。
eg:
grant
.revoke
,commit
,rollback
,savepoint
,lock
- 基本操作
- 开启MySQL服务
- 右键计算机—》管理—》服务—》启动或停止Mysql服务
- 命令行:启动:
net start musql服务名
停止:net stop mysql服务名
- 登录与退出
- 登录:
mysql -h 主机名 -u用户名 -p密码
- 退出:
exit
- 查看有哪些数据库:
show databases
- 使用一个数据库:
use 数据库名
- 新建一个数据库:
create database 数据库名
- 注:
- SQL语句不区分大小写;
- 每个语句用
;
隔开;
数据库查询
- 基本查询语句
- 查询全部列
SELECT * FROM departments
departments为表名 - 查询特定列
SELECT department_id, department_name FROM departments
- 显示表的结构
DESCRIBE employees
- 条件查询
-
WHERE
子句的使用:
SELECT employee_id, first_name, last_name,department_id
FROM employees
WHERE department_id >= 90
注: 比较运算符与逻辑运算符
BETWEEN ... AND ...
SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 AND 3500
IN
SELECT employee_id, last_name,salary,manager_id
FROM employees
WHERE manager_id IN (100,101,102)
LIKE
模糊查询,%
代表任意个字符,_
代表一个字符SELECT first_name FROM employees WHERE first_name LIKE '_O%'
IS (NOT) NULL
判断是否为空值SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL
AND
SELECT employee_id, last_name, job_id,salary FROM employees WHERE salary >=100 AND job_id LIKE '%MAN'
OR
SELECT employee_id, last_name, job_id,salary
FROM employees
WHERE salary >=100 OR job_id LIKE '%MAN'
- 排序
ORDER BY
子句,ASC(acend)
:升序 ,DESC(descend)
:降序SELECT last_name, job_id, department_id,hiredate FROM employees ORDER BY hiredate
- 按别名排序
SELECT employee_id, last_name, salary*12 annsal FROM employees ORDER BY annsal
- 多个列排序
SELECT last_name, department_id, salary FROM employees ORDER BY department_id, salary DESC
- 分组函数
用于一组数据并对一组数据返回一个值。
AVG
:平均值,SUM
:求和,MAX
:最大值,MIN
:最小值。SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM employees
- 2.
COUNT
计数函数SELECT COUNT(*) FROM employees WHERE department_id = 50
SELECT COUNT(commission_pct) FROM employees
GROUP BY
子句
将表中的数据分成若干组。SELECT department_id, AVG(salary) FROM employees GROUP BY department_id
- **注:**不能在
where
子句中使用组函数,不能再having
子句中使用组函数。 HAVING
子句
过滤分组,满足HAVING
子句中条件的分组将被显示。SELECT department_id, AVG(salary) FROM employees GROUP BY department_id HAVING AVG(salary > 7000)
- 多表查询
- 等值链接
SELECT beauty.id, `name`, boyName
FROM beauty, boys
WHERE beauty.boyfriend_id = boys.id
注: 在表中有相同的列名时,在列名之前加上表名前缀进行区分。也可以使用表的别名加列名,表的别名.列名
。
2. ON
子句创建多表链接
SELECT beauty.id, `name`, boyName
FROM beauty INNER JOIN boys
ON beauty.boyfriend_id = boys.id
3. Join链接
再叙。。。