gpt4 book ai didi

erlang - Mnesia 相当于 SQL NOT IN

转载 作者:行者123 更新时间:2023-12-01 15:23:33 24 4
gpt4 key购买 nike

我有两条记录:

-record(foo, {timestamp, name}).
-record(bar, {timestamp, name}).

我想执行一个模拟以下 SQL 查询的 Mnesia 查询

SELECT f.* FROM foo f WHERE f.timestamp NOT IN ( SELECT b.timestamp FROM boo b)

什么是有效的 Mnesia 等价物?

最佳答案

好问题!现在,我想到了两种方法。一个我们使用 qlc,另一个我们使用 mnesia 自己的带累加器的表迭代方法。这是第一个选项:

%% Here i use 'qlc', with a guard%% which ensures that the timestamp%% in the given 'foo record'%% does NOT exist in table 'bar'
query()-> Is_not_in_bar = fun(Stamp)-> case mnesia:dirty_read({bar,Stamp}) of [] -> true; _ -> false end end,
Q = qlc:q([R || R <- mnesia:table(foo),
Is_not_in_bar(R#foo.timestamp) == true])), Fun = fun(QH)-> qlc:e(QH) end, mnesia:activity(transaction,Fun,[Q],mnesia_frag).

另一种选择是迭代表 foo,同时交叉引用表 bar 中的每个时间戳。如果在 bar 中找不到,则将其添加到累计金额中。看看下面这个

%% Here i iterate table 'foo'%% for each record i find,%% i try to cross reference%% its timestamp in table 'bar'%% If its not found, then i add that%% 'foo record' into the Buffer%% I accumulate this Buffer until%% the entire table 'foo' has been %% traversed
query_vsn2()-> Iterator = fun(#foo{timestamp = T} = Rec,Buffer)-> NewBuffer = case mnesia:dirty_read({bar,T}) of [] -> [Rec|Buffer]; _ -> Buffer end, NewBuffer end, Find = fun(Loop)-> mnesia:foldl(Loop,[],foo) end, mnesia:activity(transaction,Find,[Iterator],mnesia_frag).
我想根据表的大小、应用程序和用户偏好,这些功能中的每一个都会产生影响。但是,请同时尝试这两种方法,看看哪一种能很好地融入您的应用程序。好消息是,这完全是一项读取工作,没有写入,所以我希望效率足够高。成功!

关于erlang - Mnesia 相当于 SQL NOT IN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9347753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com