Mnesia - 检查表中任一键的值

时间:2013-05-21 01:52:21

标签: erlang mnesia

我有一个使用以下记录创建的mnesia表“users”

-record(users,{username,nickname,age})

假设我有mnesia表,如下面的记录

users | username | nickname | age

users | John     | baddy    | 25 

users | Monk     | John     | 26

我有一个与表格相匹配的名字......(说“John”)..我想选择或匹配“John”作为用户名或昵称的行...我怎样才能实现这一目标?如果有人可以建议我,我会非常高兴...

由于

3 个答案:

答案 0 :(得分:1)

查看QLC - there's a simple example here on Learn You Some Erlangman page here。您可以使用布尔值匹配,例如(伪代码)(用户名== John OR nickname == John)。

答案 1 :(得分:1)

-module(wy).
-compile(export_all).

-record(users, {username, nickname, age}).
-include_lib("stdlib/include/ms_transform.hrl").

create_table()->
    mnesia:create_schema(node()),
    mnesia:start(),
    mnesia:create_table(users, [{attributes, record_info(fields, users)}]).

test()->
    Fun = fun()->
              mnesia:write(#users{username = "John", nickname = "baddy", age = 25}),
              mnesia:write(#users{username = "DaDa", nickname = "KaKa", age = 24}),
              mnesia:write(#users{username = "Monk", nickname = "John", age = 24})
          end,
    mnesia:transaction(Fun),

    Fun2 = ets:fun2ms(fun({users, UserName, NickName, Age}) when
                       UserName == "John" orelse NickName == "John" ->
                            {users, UserName, NickName, Age}
                  end), 

    mnesia:transaction(fun() -> mnesia:select(users, Fun2) end).

答案 2 :(得分:0)

select(Q)->
    case mnesia:is_transaction() of
        false -> 
            F = fun(QH)-> qlc:e(QH) end,
            mnesia:activity(transaction,F,[Q],mnesia_frag);
        true -> qlc:e(Q)
    end.

read_by_name_or_nickname(Name)->
    Data = select(qlc:q([X || X <- mnesia:table(users),
        ((X#users.username == Name) orelse (X#users.nickname == Name))])),
    Data.