Andreas
Andreas

Reputation: 167

Erlang - Mnesia - equivalent to "select distinct id from Table"

Hi is there a possibility to make a distinct select request to mnesia ?

I could copy the content of one table to ets and since ets is a hash table it could work. But i thought there is maybe a more elegant solution to this problem.

Thank you.

Upvotes: 3

Views: 1172

Answers (2)

Ciprian Ciubotariu
Ciprian Ciubotariu

Reputation: 11

For keys you can get a list of unique keys using:

mnesia:all_keys(Table).

From my tests, for bags it yields a list of unique keys.

Upvotes: 1

Jr0
Jr0

Reputation: 2173

I'm not sure if this is what you had in mind, but you could use QLC's {unique, true} option (See QLC documentation for more info).

I created a mnesia table, called test, with bag semantics. Each row consists of the table name, a Key and a Value, so my rows looked like:

1. test, 1, 1
2. test, 2, 1
3. test, 2, 2
4. test, 3, 1
5. test, 3, 2
6. test, 3, 3
... etc.

Then this simple module illustrates my approach. Notice that you have to include the qlc library and that, in my example, I am selecting distinct Keys.

-module(test).
-export([select_distinct/0]).

-include_lib("stdlib/include/qlc.hrl").

select_distinct()->
    QH = qlc:q( [K || {_TName, K, _V} <- mnesia:table(test)], {unique, true}),
    F = fun() -> qlc:eval(QH) end,
    {atomic, Result} = mnesia:transaction(F),
    Result.

Compiling and running

> c("/home/jim/test", [{outdir, "/home/jim/"}]).
> test:select_distinct(). 
> [4,1,2,3,5]

If you wanted sorted output then use the following version of the QH = ... line above

    QH = qlc:sort(qlc:q( [K || {_TName, K, _V} <- mnesia:table(test)], {unique, true})),

If you wanted to select distinct values, the following would work:

QH = qlc:sort(qlc:q( [V || {_TName, _K, V} <- mnesia:table(test)], {unique, true})),

Again, the code is just to illustrate an approach

Upvotes: 4

Related Questions