Search code examples
selecterlangmnesia

Select only one column from mnesia


how can i select only one column from mnesia? I can select onle column in ets table with this code:

ets:match(AllData_TableId, {'_', '$1','_',','_'},3),

I need something similar for mnesia.

Thank you.


Solution

  • In the examples found here: http://en.wikibooks.org/wiki/Erlang_Programming/Using_mnesia, look at how the author uses the function mnesia:match_object/1, and the consider reading it here more http://www.erlang.org/doc/man/mnesia.html#match_object-1

    However, we are advised to design our mnesia databases and/or tables in a way to avoid the use of this method. This is because it makes mnesia traverse the entire table looking for a match.

    What you need is qlc

    -include_lib("stdlib/include/qlc.hrl").
    
    select(Q)->
        case mnesia:is_transaction() of
            false -> 
                F = fun(QH)-> qlc:e(QH) end,
                %% mnesia:transaction(F);
                mnesia:activity(transaction,F,[Q],mnesia_frag);
            true -> qlc:e(Q)
        end.
    
    -record(book,{title,isbn,price,category}).
    
    book_title({book,ISBN})->
        select(qlc:q([X#book.title || X <- mnesia:table(book),X#book.isbn == ISBN])).