表的约束及代码练习

发布于:2025-03-27 ⋅ 阅读:(33) ⋅ 点赞:(0)

一.表的约束

查看表: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 = '武松';


网站公告

今日签到

点亮在社区的每一天
去签到