1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| -- 一个用户和卡是一对多,一个银行员工和卡是一对多的关系,那么用户和银行员工是多对多的关系
CREATE TABLE IF NOT EXISTS staffs (
id INT PRIMARY KEY AUTO_INCREMENT,
staff_code CHAR(10) NOT NULL COMMENT '员工号',
staff_name VARCHAR(30) NOT NULL COMMENT '员工名称',
hire_date DATE NOT NULL COMMENT '入职时间',
created_at TIMESTAMP NOT NULL default CURRENT_TIMESTAMP COMMENT '记录的创建时间',
modified_at TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '记录的变更时间'
);
INSERT INTO staffs (staff_code, staff_name, hire_date) VALUES
('35000pl', '小星', CURRENT_DATE),
('35000px', '小文', CURRENT_DATE);
INSERT cards (user_id, card_no) VALUES
(2, '6118481162710558819'),
(2, '6128482262710558819'),
(2, '6348483362710558819');
-- 给卡添加开卡柜员号
ALTER TABLE cards ADD created_staff_id INT COMMENT '开卡员工ID' AFTER created_at;
-- 添加外键关联
ALTER TABLE cards
ADD CONSTRAINT ‘staff_create_card’
FOREIGN KEY (created_staff_id)
REFERENCES staffs(id)
-- ON DELETE SET NULL -- 某个员工删除的,将 created_staff_id(关联的外键)设成 null
-- ON DELETE CASCADE -- 某个员工删除的,cards 中关联的数据会同步删除
;
-- 删除外键约束
-- ALTER TABLE cards DROP CONSTRAINT staff_create_card;
UPDATE cards
SET created_staff_id = 1
WHERE id IN (1, 3, 8);
UPDATE cards
SET created_staff_id = 2
WHERE id IN (2, 7, 9);
SELECT id, id IN (2, 7, 9) from cards; -- 可以把 where 语句输入到 select 中,验证下结果,0 代表不成立,1代表不成立
-- 表关联(三张表)
SELECT u.name, u.id_card, s.staff_code, c.* FROM -- c.* 表示取 cards 表中的所有字段
cards c
INNER JOIN users u ON c.user_id=u.id
INNER JOIN staffs s ON c.created_staff_id=s.id;
|