7

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

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

现在我在表中插入一行:

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

现在,如果我想更新这一行,并且只将 a 的值更改为 10,同时让 i 和 b 具有相同的值,我该怎么办?有没有类似“ UPDATE T SET a=10 WHERE i=1”的SQL等价物?

如果我做这样的事情:

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

该行存储为:

{rec,1,10,undefined}
4

2 回答 2

10

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

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

建议:如果你想要一些更像 SQL 语法的语法糖,可以看看 QLC。

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.

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'.

于 2009-11-30T17:01:11.233 回答
2

我相信您需要阅读“行”,更新您需要的任何字段,然后在“事务”中写回结果和所有这些操作。

于 2009-11-30T17:00:04.010 回答