一.表的約束
查看表:mysql> select * from t_hero;
1.設置t_hero的主鍵為t_id
alter table t_hero add primary key(t_id);
?2.設置t_hero t_id屬性非空
alter table t_hero modify t_id int not null;
3.設置name屬性為非空非重復?
alter table t_hero modify name varchar(255) not null;
alter table t_hero add unique (name);
4.設置檢查約束
alter table t_hero add constraint chk_gender check(sex in ('男', '女'));
desc t_hero;
二,句練習
1.基本查詢語句
-- 查詢所有數據
select * from t_hero;
?
-- 查詢需要的字段信息
SELECT t_id, name, age FROM t_hero;
-- 查詢一個字段,一個等值條件
select name from t_hero where t_id = 1;
?
?2.聚合函數使用
select count(*) from t_hero;
如果想要使用別稱:
?3.常見條件查詢
SELECT t_id, name, sex FROM t_hero WHERE t_id IN (2, 4);
?4.模糊查詢
select * from t_hero where name like "豬%";
5.邏輯運算符and
SELECT t_id, name, sex FROM t_hero WHERE name LIKE '賈%' AND sex = '男';
6. 分組查詢
select sex from t_hero group by sex;
這里可以和前面的聚合函數配合使用:
SELECT sex, COUNT(*) AS total
FROM t_hero
GROUP BY sex;
7.結果排序?
SELECT * FROM t_hero WHERE t_id <= 6 ORDER BY t_id;
三.外鍵與多表關聯
1.創建用于外鍵關聯的表
我已經創建好了如圖:
2.創建外鍵相關字段
alter table t_hero add book int;
?
創建好之后,查看一下:desc t_hero;
3.創建外鍵約束
alter table t_hero
add constraint fk_hero_book
foreign key (book) references book(b_id);
alter table t_hero
:指定修改目標表為?t_hero
。add constraint fk_hero_book
:添加名為?fk_hero_book
?的約束。foreign key (book)
:聲明?t_hero
?表的?book
?列為外鍵。references book(b_id)
:指定該外鍵關聯?book
?表的主鍵?b_id
。
4.多表關聯
UPDATE t_hero SET book = 1 WHERE name = '豬八戒'; UPDATE t_hero SET book = 3 WHERE name = '賈寶玉'; UPDATE t_hero SET book = 2 WHERE name = '貂蟬'; UPDATE t_hero SET book = 4 WHERE name = '武松';