2、Insert / Update 操作
  mnesia是根据主键去更新记录的,如果主键不存在则插入
%%===============================================
%%    insert into y_account (id,account,password) values(5,"xiaohong","123")
%%     on duplicate key update account="xiaohong",password="123";
%%===============================================
%% 使用 mnesia:write
F = fun() ->
Acc = #y_account{id = 5, account="xiaohong", password="123"},
mnesia:write(Acc)
end,
mnesia:transaction(F).
  3、Where 查询
%%===============================================
%%    select account from y_account where id>5
%%===============================================
%% 使用 mnesia:select
F = fun() ->
MatchHead = #y_account{id = '$1', account = '$2', _ = '_' },
Guard = [{'>', '$1', 5}],
Result = ['$2'],
mnesia:select(y_account, [{MatchHead, Guard, Result}])
end,
mnesia:transaction(F).
%% 使用 qlc
F = fun() ->
Q = qlc:q([E#y_account.account || E <- mnesia:table(y_account), E#y_account.id>5]),
qlc:e(Q)
end,
mnesia:transaction(F).
  如果查找主键 key=X 的记录,还可以这样子查询:
%%===============================================
%%   select * from y_account where id=5
%%===============================================
F = fun() ->
mnesia:read({y_account,5})
end,
mnesia:transaction(F).
    如果查找非主键 field=X 的记录,可以如下查询:
%%===============================================
%%   select * from y_account where account='xiaomin'
%%===============================================
F = fun() ->
MatchHead = #y_account{ id = '_', account = "xiaomin", password = '_' },
Guard = [],
Result = ['$_'],
mnesia:select(y_account, [{MatchHead, Guard, Result}])
end,
mnesia:transaction(F).

  4、Order By 查询
%%===============================================
%%   select * from y_account order by id asc
%%===============================================
%% 使用 qlc
F = fun() ->
Q = qlc:q([E || E <- mnesia:table(y_account)]),
qlc:e(qlc:keysort(2, Q, [{order, ascending}]))
end,
mnesia:transaction(F).
%% 使用 qlc 的第二种写法
F = fun() ->
Q = qlc:q([E || E <- mnesia:table(y_account)]),
Order = fun(A, B) ->
B#y_account.id > A#y_account.id
end,
qlc:e(qlc:sort(Q, [{order, Order}]))
end,
mnesia:transaction(F).