mysql默认值另一列_MySQL:另一个表列中列的默认值

bd96500e110b49cbb3cd949968f18be7.png

Consider you have table USER which has primary key on field USER_ID. And every table in your db should contain MODIFIED_BY field with id of actual user. My aim is to specify default value on that field which equals id of user with appropriate name. F.E. you have user with name system and you want every record of every table to have id of this user in MODIFIED_BY field. As well you want all the new records to satisfy this.

解决方案

Assuming that you are referring to other sorts of users than database users (e.g. 'registered users'), maybe triggers are the solution to your problem. With two triggers, one fired when inserting and one when updating, you can specify the value of a modified_at-column using custom code, e.g. select user_id from ... where ...

Please check the following sample code, which should directly answer your question; hope it solves your problem. Otherwise, please give us more information / some more context.

DELIMITER |

drop table if exists sometable

|

CREATE TABLE `sometable` (

`somecolumn` int(11) DEFAULT NULL,

`modified_by` int(11) DEFAULT NULL

)

|

drop table if exists registered_user

|

CREATE TABLE registered_user (

user_id integer primary key,

name varchar(50)

)

|

drop trigger if exists sometable_inserted

|

drop trigger if exists sometable_modified

|

CREATE TRIGGER sometable_inserted BEFORE INSERT ON sometable

FOR EACH ROW

BEGIN

SET new.modified_by := (select user_id from registered_user where name=@name);

END;

|

CREATE TRIGGER sometable_modified BEFORE UPDATE ON sometable

FOR EACH ROW

BEGIN

SET new.modified_by := (select user_id from registered_user where name=@name);

END;

|

DELIMITER ;

insert into registered_user values (5, 'joe');

insert into registered_user values (6, 'sam');

set @name='sam';

insert into sometable(somecolumn) values (1);

insert into sometable(somecolumn) values (2);

set @name='joe';

update sometable set somecolumn = 3 where somecolumn = 2;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值