Erlang:Mnesia:更新行中的单个字段值 [英] Erlang : Mnesia : Updating a single field value in a row

查看:114
本文介绍了Erlang:Mnesia:更新行中的单个字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mnesia表,包含使用记录创建的三个字段i,a和b。

I have an mnesia table with three fields, i, a and b, created using the record

-record(rec, {i, a,b}).

现在我在表格中插入一行:

Now I insert a row into the table as:

mnesia:transaction( fun() -> mnesia:write("T", #rec{i=1, a=2, b=3}, write) end ).

现在,如果我想更新此行, 10,而使i和b具有相同的值?是否有任何SQL等效项如 UPDATE T SET a = 10 WHERE i = 1

Now what do I do if I want to update this row, and change only the value of a to 10, while leaving i and b with the same values? Is there any SQL equivalent like "UPDATE T SET a=10 WHERE i=1"?

像这样:

mnesia:transaction( fun() -> mnesia:write("T", #rec{i=1, a=10}, write) end )

行存储为:

{rec,1,10,undefined}


推荐答案

如果在mnesia中使用,此函数的值将更新:transaction

The value of this function will update a if used in a mnesia:transaction

update_a(Tab, Key, Value) ->
  fun() ->
    [P] = mnesia:wread({Tab, Key}),
    mnesia:write(P#pixel{a=Value})
  end.

建议:如果你想要一些语法糖更像SQL语法,

Suggestion: have a peek at QLC if you want some syntax sugar that is more like the SQL syntax.

性能当然是最好的基准,但QLC有开销,我不知道它们与其他细节相比。我只是想你的SQL示例你更新所有有 i = 1 的记录。使用QLC提取这组记录比mnesia调用更漂亮。

The performance is of course best benchmarked, but QLC has overhead, I'm not sure they are relevant compared to the other details. I just figured that the SQL example you gave would update all records that have i=1. Using QLC to extract that set of records is prettier than mnesia calls.

还要注意, wread 锁定在记录上直接,因为我们提前知道,我们将更新该记录。这是一个微优化,以避免首先读锁,然后改变我们的想法,并获得写锁。我没有在很长时间的基准。

Also to notice, wread claims a write lock on the record directly, because we know ahead of time that we will update that record. That's a micro-optimization to avoid first a read lock, then change our mind and get a write lock. I haven't benchmarked that in a long time though.

如果性能仍然是一个问题,你应该看看使用脏操作的各种方法。但你真的应该尝试弄清楚你每秒需要多少交易,足够快。

If performance is still an issue you should look at various approaches where you use dirty operations. But you really should try to figure out how many transactions per second you need, to be 'fast enough'.

这篇关于Erlang:Mnesia:更新行中的单个字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆