mysql视图字段默认值,基于视图的MySQL默认值

Basically I have a bunch of views based on a simple discriminator column (eg. CREATE VIEW tablename AS SELECT * FROM tablename WHERE discrcolumn = "discriminator value").

Upon inserting a new row into this view, it should insert "discriminator value" into discrcolumn.

I tried this, but apparently MySQL doesn't figure this out itself, as it throws an error "Field of view viewname underlying table does not have a default value". The discriminator column is set to NOT NULL of course.

How do I mend this? Perhaps a pre-insert trigger?

UPDATE: Triggers won't work on views, see below comment.

Would it work to create a trigger on the table which uses a variable, and set that variable at establishing the connection? For each connection the value of that variable would be the same, but it could differ from other connections.

EDIT:

This appears to work...

Setup:

CREATE TRIGGER insert_[tablename] BEFORE INSERT ON [tablename]

FOR EACH ROW SET NEW.[discrcolumn] = @variable

Runtime:

SET @variable = [descrvalue];

INSERT INTO [viewname] ([columnlist]) VALUES ([values]);

解决方案

I don't think you need anything quite so complicated as that. If you created a view such as

CREATE VIEW MYVIEW AS

SELECT COLUMN1,

COLUMN2,

DISCRIMINATOR_COLUMN

FROM MYTABLE

WHERE DISCRIMINATOR_COLUMN = 1;

you could then insert into this view thus...

INSERT INTO MYVIEW (COLUMN1,

COLUMN2,

DISCRIMINATOR_COLUMN)

VALUES (1, 2, 3)

and the view should update correctly if all the columns in the table that aren't present in the view have suitable defaults. Note that the new value in DISCRIMINATOR_COLUMN needn't be the value picked out in the view, although naturally it won't appear in the view when next selected unless it is.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值