Py学习  »  DATABASE

MySQL将默认值设置为其他表中的其他列

Alexander • 5 年前 • 2283 次点击  

艺术家 , . 我想知道是否有任何方法可以设置 这样地 (艺术家、知名度、舞台、声誉) 可以这样做吗?还是在插入时必须手动设置成本值? enter image description here

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54305
 
2283 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Code wizard
Reply   •   1 楼
Code wizard    5 年前

SQL-外键 广告


外键是用于将两个表链接在一起的键。有时也称为引用键。

外键是一列或列的组合,其值与其他表中的主键匹配。

如果表在任何字段上定义了主键,则不能有两条记录具有该字段的相同值。

考虑下两个表的结构。

客户表

ID INT不为空, 名称VARCHAR(20)不为空, 年龄INT不为空, 工资小数(18,2),
主键(ID) 订单表

创建表顺序( 日期日期时间, 客户ID INT引用客户(ID), 金额加倍, 主键(ID) ); 如果已创建ORDERS表,但尚未设置外键,则使用通过更改表指定外键的语法。

更改表顺序 添加外键(客户ID)引用客户(ID);

GMB
Reply   •   2 楼
GMB    5 年前

计算列不能引用其他表中的列(它只看到自己表行上的值)。

相反,您可以使用一个触发器来触发 event cost 从其他表/列:

delimiter |
create trigger trg_event_price
before insert on event
for each row
begin
    if new.cost is null then
        set new.cost = 
            (select popularity from artist where id = new.artist_id)
            * (select reputation from stage where id = new.stage_id)
        ;
    end if;
end
|
delimiter ;

设置好这个触发器后,就可以忽略列 成本 什么时候 insert 事件 ,然后让触发器处理它:

insert into event (artist_id, stage_id) values(1, 5);
-- "cost" will be computed from the popularity of artist 1 and the reputation of stage 5