erlang mnesia 數據庫實現SQL查詢

Mnesia是一個分佈式數據庫管理系統,適合於電信和其它需要持續運行和具備軟實時特性的Erlang應用,越來越受關注和使用,但是目前Mnesia資料卻不多,很多都只有官方的用戶指南。下面的內容將着重說明  Mnesia 數據庫如何實現SQL查詢,實現select / insert / update / where / order by / join / limit / delete等SQL操作。
 

示例中表結構的定義:

%% 賬號表結構  
-record( y_account,{ id, account, password }).  

%% 資料表結構
-record( y_info, { id, nickname, birthday, sex }).   

1、Create Table / Delete Table 操作

%%===============================================
%%  create table y_account ( id int, account varchar(50),
%%   password varchar(50),  primary key(id)) ;
%%===============================================

%% 使用 mnesia:create_table
mnesia:create_table( y_account,[{attributes, record_info(fields, y_account)} , {type,set}, {disc_copies, [node()]} ]).

%%===============================================
%%  drop table y_account;
%%===============================================

%% 使用 mnesia:delete_table
mnesia:delete_table(y_account) .

注:參數意義可以看文檔,{type,set} 表示id作爲主鍵,不允許id重複,如果改爲 {type,bag},id可以重複,但整條記錄不能重複

2、Select 查詢

%%===============================================
%%  select * from y_account
%%===============================================

%% 使用 mnesia:select
F = fun() ->
	MatchHead = #y_account{ _ = '_' },
	Guard = [],
	Result = ['$_'],
	mnesia:select(y_account, [{MatchHead, Guard, Result}])
end,
mnesia:transaction(F).

%% 使用 qlc
F = fun() ->
	Q = qlc:q([E || E <- mnesia:table(y_account)]),
	qlc:e(Q)
end,
mnesia:transaction(F).

查詢部分字段的記錄

%%===============================================
%%  select id,account from y_account
%%===============================================

%% 使用 mnesia:select
F = fun() ->
	MatchHead = #y_account{id = '$1', account = '$2', _ = '_' },
	Guard = [],
	Result = ['$$'],
	mnesia:select(y_account, [{MatchHead, Guard, Result}])
end,
mnesia:transaction(F).

%% 使用 qlc
F = fun() ->
	Q = qlc:q([[E#y_account.id, E#y_account.account] || E <- mnesia:table(y_account)]),
	qlc:e(Q)
end,
mnesia:transaction(F).

3、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).

4、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).

5、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).

6、Join 關聯表查詢

%%===============================================
%%   select y_info.* from y_account join y_info on (y_account.id = y_info.id)
%%      where y_account.account = 'xiaomin'
%%===============================================

%% 使用 qlc
F = fun() ->
	Q = qlc:q([Y || X <- mnesia:table(y_account),
		X#y_account.account =:= "xiaomin",
		Y <- mnesia:table(y_info),
		X#y_account.id =:= Y#y_info.id
	]),
	qlc:e(Q)
end,
mnesia:transaction(F).

7、Limit 查詢

%%===============================================
%%   select * from y_account limit 2
%%===============================================

%% 使用 mnesia:select
F = fun() ->
	MatchHead = #y_account{ _ = '_' }, 
	mnesia:select(y_account, [{MatchHead, [], ['$_']}], 2, none)
end,
mnesia:transaction(F).

%% 使用 qlc
F = fun() ->
	Q = qlc:q([E || E <- mnesia:table(y_account)]),
	QC = qlc:cursor(Q),
	qlc:next_answers(QC, 2)
end,
mnesia:transaction(F).

8、Select count(*) 查詢

%%===============================================
%%   select count(*) from y_account
%%===============================================

%% 使用 mnesia:table_info
F = fun() ->
	mnesia:table_info(y_account, size)
end,
mnesia:transaction(F).

9、Delete 查詢

%%===============================================
%%   delete from y_account where id=5
%%===============================================

%% 使用 mnesia:delete
F = fun() ->
	mnesia:delete({y_account, 5})
end,
mnesia:transaction(F).

注:使用qlc模塊查詢,需要在文件頂部聲明“-include_lib("stdlib/include/qlc.hrl").”,否則編譯時會產生“Warning: qlc:q/1 called, but "qlc.hrl" not included”的警告。

實踐

方法3使用的是事務,也可以使用方法2的mnesia:dirty_select。

方法1:
F = fun () ->
MatchHead = #person{name='$1', sex=male, age='$2', _='_'},
Guard = [{'>', '$2', 30}],
Result = ['$1'],
L = mnesia:select(Tab,[{MatchHead, Guard, Result}])
end,
mnesia:transaction(F).

方法2:
MatchHead = #person{name='$1', sex=male, age='$2', _='_'},  % 也可包含等於條件   name=Name
Guard = [{'>', '$2', 30}], %條件 > == <
Result = ['$1'],  %結果  '$n'返回變量$n;'$$'返回所有  $變量;  '$_'返回整行;
mnesia:dirty_select(Tab,[{MatchHead, Guard, Result}]).

方法3:
F = fun() ->  
    MatchHead = #?ONLINE_TAB{type = '$1', user = '$2', _ = '_' },  
    Guard = [],  
    Result = ['$1'],
    Types = mnesia:select(?ONLINE_TAB, [{MatchHead, Guard, Result}]),
    io:format("topic list : ~p~n", [Types]),
    %lists:foreach(fun(Type) -> plugin:start(Type) end, Types)
    [plugin:start(Type) || Type <- Types]
    end,  
    mnesia:transaction(F).

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章