简体   繁体   English

显示列表中具有特定元素的所有记录

[英]Display all records with a certain element in lists

How to use lists:member(User,users) in the match_object command?? 如何使用list:match_object命令中的成员(用户,用户)? I have several records in which "users" is a list contain different users , i want to display the records which contain a certain user . 我有几条记录,其中“users”是一个包含不同用户的列表,我想显示包含某个用户的记录。

find(User) ->
mnesia:transaction(fun () -> 
 case mnesia:match_object(#updt{**users==[User]**, _='_'}) of
    [Y] ->io:format("Records found for the user : ~p~n", [Y]);
    [] ->  io:format("No group found with the user : ~p ~n",[User])
end
end).`

Basically what you are doing in a mnesia:match_object/1 is supplying a pattern to match, no more no less. 基本上你在mnesia:match_object/1中做的是mnesia:match_object/1提供匹配的模式,不多也不少。 And in a pattern you can only match data and cannot specify a call to a function. 在模式中,您只能匹配数据,不能指定对函数的调用。 As erlang does not have a patten data type we fake it by supplying a structure which is interpreted as a pattern. 由于erlang没有patten数据类型,我们通过提供一个被解释为模式的结构来伪造它。

Unfortunately using mnesia:select/2 will not help here. 不幸的是使用mnesia:select/2在这里没有帮助。 While a match spec has a "guard" you are only allowed to do typical guard things in it and calling general functions are not allowed. 虽然匹配规范有“防守”,但您只能在其中执行典型的防护,并且不允许调用一般功能。

Note that both mnesia:match_object/1 and mnesia:select/2 return the whole objects which match. 请注意, mnesia:match_object/1mnesia:select/2返回匹配的整个对象。

I see 2 options to solve your problem: 我看到2个选项可以解决您的问题:

use 采用

mensia:foldl(fun({updt,I,L},Acc) -> 
                case lists:member(User,L) of
                    true -> [I|Acc];
                    _ -> Acc
                end,[],Table)

or maintain a second table which records what you need ({new_table,User,[I...]}) 或维护第二个表格,记录您的需求({new_table,User,[I ...]})

You should choose depending on the frequency of update request, query request, the size of the table and if there are concurrent accesses or not. 您应该根据更新请求的频率,查询请求,表的大小以及是否存在并发访问来选择。

You don't have to use match_object. 您不必使用match_object。 I have answered a similar question: 我也回答了类似的问题:

[answered question][1] https://stackoverflow.com/a/28762454/ [回答问题] [1] https://stackoverflow.com/a/28762454/

Basically you can query the database like you would with a SQL DB using the method i specified in the answered question. 基本上,您可以使用我在答案问题中指定的方法查询数据库,就像使用SQL DB一样。 You can use lists:member/2 to find matches. 您可以使用list:member / 2来查找匹配项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM