[英]Can I specify a query as a field's default value?
I mean something like: 我的意思是:
create table Measures (
id_user int,
date timestamp,
measure_1 double default 'select measure_1 from Measures where data = '**/**/****'',
measure_2 double default 'select measure_1 from Measures where data = '**/**/****'');
In this way I insert the value of the last measure saved in the db.. Is it possible? 这样我就插入了db中保存的最后一个度量值。是否可能?
11.7 Data Type Default Values 11.7数据类型默认值
... the default value must be a constant; ...默认值必须是常量; it cannot be a function or an expression. 它不能是一个功能或表达。
You'll have to do this on application level, or in a trigger as suggested by @Timekiller. 您必须在应用程序级别或@Timekiller建议的触发器中执行此操作。
You can do that via a before-insert trigger . 您可以通过插入前触发器来完成此操作 。
Check if NEW.measure_1
is null, and if it is, then perform select and store results. 检查NEW.measure_1
是否为空,如果是,则执行选择和存储结果。
UPD: UPD:
Right, I was in a bit of a hurry yesterday, and forgot to give an example later. 对,我昨天有点匆忙,以后忘了举个例子。 Trigger is a good replacement for complex default value - it will work transparently, will look just like the default value from database user standpoint, and you won't have to do anything on the application level, since triggers are stored in the database itself. 触发器是复杂默认值的良好替代 - 它将透明地工作,看起来就像数据库用户角度的默认值,并且您不必在应用程序级别上执行任何操作,因为触发器存储在数据库本身中。 It will look something like this: 它看起来像这样:
CREATE TRIGGER `measures_bi_trigger` BEFORE INSERT ON `Measures`
FOR EACH ROW BEGIN
if NEW.measure_1 is null then
SET NEW.measure_1 = (select measure_1 from Measures where ... limit 1);
end if;
if NEW.measure_2 is null then
SET NEW.measure_2 = (select measure_2 from Measures where ... limit 1);
end if;
END
It's not exactly clear what should be in your where
condition, so you'll have to substitute ...
yourself. 它不完全清楚应该在你的什么where
状况,所以你需要替换...
你自己。 Note that your query should return exactly one row, so either use an aggregate function like MAX
or order by ... limit 1
. 请注意,您的查询应该只返回一行,因此要么使用MAX
类的聚合函数,要么使用order by ... limit 1
。 If your query returns no rows, NULL
will be inserted. 如果查询未返回任何行,则将插入NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.