Mnesia是一个分布式数据库管理系统,适合于电信和其它需要持续运行和具备软实时特性的Erlang应用,越来越受关注和使用,但是目前Mnesia资料却不多,很多都只有官方的用户指南。下面的内容将着重说明  Mnesia 数据库如何实现SQL查询,实现select / insert / update / where / order by / join / limit / delete等SQL操作。

示例中表结构的定义:

  1. %% 账号表结构
  2. -record( y_account,{ id, account, password }).
  3. %% 资料表结构
  4. -record( y_info, { id, nickname, birthday, sex }).

1、Create Table / Delete Table 操作

  1. %%===============================================
  2. %%  create table y_account ( id int, account varchar(50),
  3. %%   password varchar(50),  primary key(id)) ;
  4. %%===============================================
  5. %% 使用 mnesia:create_table
  6. mnesia:create_table( y_account,[{attributes, record_info(fields, y_account)} ,
  7. {type,set}, {disc_copies, [node()]} ]).
  8. %%===============================================
  9. %%  drop table y_account;
  10. %%===============================================
  11. %% 使用 mnesia:delete_table
  12. mnesia:delete_table(y_account) .

注:参数意义可以看文档,{type,set} 表示id作为主键,不允许id重复,如果改为 {type,bag},id可以重复,但整条记录不能重复

2、Select 查询

查询全部记录

  1. %%===============================================
  2. %%  select * from y_account
  3. %%===============================================
  4. %% 使用 mnesia:select
  5. F = fun() ->
  6. MatchHead = #y_account{ _ = '_' },
  7. Guard = [],
  8. Result = ['$_'],
  9. mnesia:select(y_account, [{MatchHead, Guard, Result}])
  10. end,
  11. mnesia:transaction(F).
  12. %% 使用 qlc
  13. F = fun() ->
  14. Q = qlc:q([E || E <- mnesia:table(y_account)]),
  15. qlc:e(Q)
  16. end,
  17. mnesia:transaction(F).

查询部分字段的记录

  1. %%===============================================
  2. %%  select id,account from y_account
  3. %%===============================================
  4. %% 使用 mnesia:select
  5. F = fun() ->
  6. MatchHead = #y_account{id = '$1', account = '$2', _ = '_' },
  7. Guard = [],
  8. Result = ['$$'],
  9. mnesia:select(y_account, [{MatchHead, Guard, Result}])
  10. end,
  11. mnesia:transaction(F).
  12. %% 使用 qlc
  13. F = fun() ->
  14. Q = qlc:q([[E#y_account.id, E#y_account.account] || E <- mnesia:table(y_account)]),
  15. qlc:e(Q)
  16. end,
  17. mnesia:transaction(F).

3、Insert / Update 操作

mnesia是根据主键去更新记录的,如果主键不存在则插入

  1. %%===============================================
  2. %%    insert into y_account (id,account,password) values(5,"xiaohong","123")
  3. %%     on duplicate key update account="xiaohong",password="123";
  4. %%===============================================
  5. %% 使用 mnesia:write
  6. F = fun() ->
  7. Acc = #y_account{id = 5, account="xiaohong", password="123"},
  8. mnesia:write(Acc)
  9. end,
  10. mnesia:transaction(F).

4、Where 查询

  1. %%===============================================
  2. %%    select account from y_account where id>5
  3. %%===============================================
  4. %% 使用 mnesia:select
  5. F = fun() ->
  6. MatchHead = #y_account{id = '$1', account = '$2', _ = '_' },
  7. Guard = [{'>', '$1', 5}],
  8. Result = ['$2'],
  9. mnesia:select(y_account, [{MatchHead, Guard, Result}])
  10. end,
  11. mnesia:transaction(F).
  12. %% 使用 qlc
  13. F = fun() ->
  14. Q = qlc:q([E#y_account.account || E <- mnesia:table(y_account), E#y_account.id>5]),
  15. qlc:e(Q)
  16. end,
  17. mnesia:transaction(F).

如果查找主键 key=X 的记录,还可以这样子查询:

  1. %%===============================================
  2. %%   select * from y_account where id=5
  3. %%===============================================
  4. F = fun() ->
  5. mnesia:read({y_account,5})
  6. end,
  7. mnesia:transaction(F).

如果查找非主键 field=X 的记录,可以如下查询:

  1. %%===============================================
  2. %%   select * from y_account where account='xiaomin'
  3. %%===============================================
  4. F = fun() ->
  5. MatchHead = #y_account{ id = '_', account = "xiaomin", password = '_' },
  6. Guard = [],
  7. Result = ['$_'],
  8. mnesia:select(y_account, [{MatchHead, Guard, Result}])
  9. end,
  10. mnesia:transaction(F).

5、Order By 查询

  1. %%===============================================
  2. %%   select * from y_account order by id asc
  3. %%===============================================
  4. %% 使用 qlc
  5. F = fun() ->
  6. Q = qlc:q([E || E <- mnesia:table(y_account)]),
  7. qlc:e(qlc:keysort(2, Q, [{order, ascending}]))
  8. end,
  9. mnesia:transaction(F).
  10. %% 使用 qlc 的第二种写法
  11. F = fun() ->
  12. Q = qlc:q([E || E <- mnesia:table(y_account)]),
  13. Order = fun(A, B) ->
  14. B#y_account.id > A#y_account.id
  15. end,
  16. qlc:e(qlc:sort(Q, [{order, Order}]))
  17. end,
  18. mnesia:transaction(F).

6、Join 关联表查询

  1. %%===============================================
  2. %%   select y_info.* from y_account join y_info on (y_account.id = y_info.id)
  3. %%      where y_account.account = 'xiaomin'
  4. %%===============================================
  5. %% 使用 qlc
  6. F = fun() ->
  7. Q = qlc:q([Y || X <- mnesia:table(y_account),
  8. X#y_account.account =:= "xiaomin",
  9. Y <- mnesia:table(y_info),
  10. X#y_account.id =:= Y#y_info.id
  11. ]),
  12. qlc:e(Q)
  13. end,
  14. mnesia:transaction(F).

7、Limit 查询

  1. %%===============================================
  2. %%   select * from y_account limit 2
  3. %%===============================================
  4. %% 使用 mnesia:select
  5. F = fun() ->
  6. MatchHead = #y_account{ _ = '_' },
  7. mnesia:select(y_account, [{MatchHead, [], ['$_']}], 2, none)
  8. end,
  9. mnesia:transaction(F).
  10. %% 使用 qlc
  11. F = fun() ->
  12. Q = qlc:q([E || E <- mnesia:table(y_account)]),
  13. QC = qlc:cursor(Q),
  14. qlc:next_answers(QC, 2)
  15. end,
  16. mnesia:transaction(F).

8、Select count(*) 查询

  1. %%===============================================
  2. %%   select count(*) from y_account
  3. %%===============================================
  4. %% 使用 mnesia:table_info
  5. F = fun() ->
  6. mnesia:table_info(y_account, size)
  7. end,
  8. mnesia:transaction(F).

9、Delete 查询

  1. %%===============================================
  2. %%   delete from y_account where id=5
  3. %%===============================================
  4. %% 使用 mnesia:delete
  5. F = fun() ->
  6. mnesia:delete({y_account, 5})
  7. end,
  8. mnesia:transaction(F).

注:使用qlc模块查询,需要在文件顶部声明“-include_lib("stdlib/include/qlc.hrl").”,否则编译时会产生“Warning: qlc:q/1 called, but "qlc.hrl" not included”的警告。

更新说明:

2013/11/20 补充了 mnesia:select 方式的 limit 查询

erlang mnesia 数据库实现SQL查询的更多相关文章

  1. oracle数据库元数据SQL查询

    oracle数据库经典SQL查询 .查看表空间的名称及大小 select t.tablespace_name, round(sum(bytes/(1024*1024)),0) ts_size from ...

  2. erlang mnesia 数据库查询

    Mnesia是一个分布式数据库管理系统,适合于电信和其它需要持续运行和具备软实时特性的Erlang应用,越来越受关注和使用,但是目前Mnesia资料却不多,很多都只有官方的用户指南.下面的内容将着重说 ...

  3. erlang mnesia数据库设置主键自增

    Mnesia是erlang/otp自带的分布式数据库管理系统.mnesia配合erlang的实现近乎理想,但在实际使用当中差强人意,总会有一些不足.mnesia数据表没有主键自增的功能,但在mnesi ...

  4. erlang mnesia数据库简单应用

    mnesia是erlang自带的分布式数据库,基于ets和dets实现的.mnesia兼顾了dets的持久性和ets的高性能,可以自动在多个erlang节点间同步数据库.最关键的是,mnesia实现了 ...

  5. Python全栈 MySQL 数据库 (SQL查询、备份、恢复、授权)

    ParisGabriel              每天坚持手写  一天一篇  决定坚持几年 为了梦想为了信仰    开局一张图   今天接着昨天的说   索引有4种:      普通 索引 :ind ...

  6. Android adb使用sqlite3对一个数据库进行sql查询

    sqlite是Android下集成的一个轻量级数据库,我们可以通过adb程序进入数据库命令行,对数据进行查询,具体操作如下: ①打开windows的cmd ②输入adb shell.此时进入了该安卓系 ...

  7. 在数据库中sql查询很快,但在程序中查询较慢的解决方法

    在写java的时候,有一个方法查询速度比其他方法慢很多,但在数据库查询很快,原来是因为程序中使用参数化查询时参数类型错误的原因 select * from TransactionNo, fmis_Ac ...

  8. [转载]Oracle数据库基础--SQL查询经典例题

    Oracle基础练习题,采用Oracle数据库自带的表,适合初学者,其中包括了一些简单的查询,已经具有Oracle自身特点的单行函数的应用 本文使用的实例表结构与表的数据如下: emp员工表结构如下: ...

  9. Oracle数据库基础--SQL查询经典例题

    Oracle基础练习题,采用Oracle数据库自带的表,适合初学者,其中包括了一些简单的查询,已经具有Oracle自身特点的单行函数的应用 本文使用的实例表结构与表的数据如下: emp员工表结构如下: ...

随机推荐

  1. raise_application_error用法

    我们经常通过dbms_output.put_line来输出异常信息,但有时需要把异常信息返回给调用的客户端.此时我们用raise_application_error,允许用户在pl/sql中返回用户自 ...

  2. Device eth0 does not seem to be present

    解决办法: 首先,打开/etc/udev/rules.d/70-persistent-net.rules内容如下面例子所示: # vi /etc/udev/rules.d/70-persistent- ...

  3. c#教程之事件处理函数的参数

    事件处理函数一般有两个参数,第一个参数(object sender)为产生该事件的对象的属性Name的值,例如上例单击标题为红色的按钮,第一个参数sender的值为button1.如上例标题为红色的按 ...

  4. EXTJS 4.2 资料 跨域的问题

    关于跨域,在项目开发中难免会遇到:之前笔者是用EXTJS3.0开发项目的,在开发过程中遇到了关于跨域的问题,但是在网上找到资料大部分都是ExtJs4.0以上版本的 在ExtJs中 例如:Ext.Aja ...

  5. Xcode 合并分支报错

    原理和操作步骤见如下转载的两篇文章, 我所使用的 svn 客户端软件是 Mac 下面的 Versions.app v1.06 这个版本包含一个多人开发的bug bug 的解决方案见我之前转载的两篇文章 ...

  6. [转]StructLayout特性

    转自:http://www.cnblogs.com/JessieDong/archive/2009/07/21/1527553.html StructLayout特性 StructLayout特性   ...

  7. 【数学/扩展欧几里得/Lucas定理】BZOJ 1951 :[Sdoi 2010]古代猪文

    Description “在那山的那边海的那边有一群小肥猪.他们活泼又聪明,他们调皮又灵敏.他们自由自在生活在那绿色的大草坪,他们善良勇敢相互都关心……” ——选自猪王国民歌 很久很久以前,在山的那边 ...

  8. The7th Zhejiang Provincial Collegiate Programming Contest->Problem A:A - Who is Older?

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3322 可以看样例猜题意的水题. #include<bits/stdc ...

  9. 关闭MyEclipse的Quick Update

    关闭MyEclipse的Quick Update, Windows > Preferences > MyEclipse > Community Essentials, 把选项 &qu ...

  10. Unity3D NGUI自适应屏幕分辨率(2014/4/17更新)

    原地址:http://blog.csdn.net/asd237241291/article/details/8126619 原创文章如需转载请注明:转载自 脱莫柔Unity3D学习之旅 本文链接地址: ...