使用DDL创建数据库&数据表时需要注意什么?
在 DDL 中,我们常用的功能是增删改,分别对应的命令是 CREATE、DROP 和 ALTER。
CREATE DATABASE nba; // 创建一个名为nba的数据库
DROP DATABASE nba; // 删除一个名为nba的数据库
CREATE TABLE player (
player_id int(11) NOT NULL AUTO_INCREMENT,
player_name varchar(255) NOT NULL
);
DROP TABLE IF EXISTS player
;
CREATE TABLE player
(
player_id
int(11) NOT NULL AUTO_INCREMENT,
team_id
int(11) NOT NULL,
player_name
varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
height
float(3, 2) NULL DEFAULT 0.00,
PRIMARY KEY (player_id
) USING BTREE,
UNIQUE INDEX player_name
(player_name
) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
排序规则是utf8_general_ci,代表对大小写不敏感,如果设置为utf8_bin,代表对大小写敏感,
修改表结构
- 增加字段
ALERT TABLE player ADD(age int(11));
- 修改字段名
ALERT TABLE palyer RENAME COLUMN age to player_age;
- 修改字段类型
ALERT TABLE player MODIFY (player_age float(3,1));
- 删除字段
ALERT TABLE player DROP COLUMN player_age;
常见约束
主键约束
外键约束
唯一性约束
NOT NULL 约束
DEFAULT
CHECK约束
设计数据表的原则
1 数据表的个数越少越好
2 数据表中的字段个数越少越好
3 数据表中联合主键的字段个数越少越好
4 使用主键和外键越多越好
SQL检索数据
Select 执行顺序
关键字顺序
select > from > where > group by > having > order by
执行顺序
select > where > group by > having > select的字段 》 distinct > order by > limit
SELECT DISTINCT player_id, player_name, count(*) as num #顺序5
FROM player JOIN team ON player.team_id = team.team_id #顺序1
WHERE height > 1.80 #顺序2
GROUP BY player.team_id #顺序3
HAVING num > 2 #顺序4
ORDER BY num DESC #顺序6
LIMIT 2 #顺序7