how to lookup last record in dataset in Mnesia?

Gaspar Chilingarov nm@REDACTED
Wed Jun 7 18:15:45 CEST 2006


hans.bolinder@REDACTED wrote:
> [Gaspar Chilingarov:]
>> I have a table in Mnesia, which I with to filter by some field(s) and
>> fetch one record with maximal ID (ie. last inserted).
>>
>> (SQL equivalent: SELECT MAX(ID) FROM table WHERE foo_field = 'bar' and
>> user_name = 'Alice')
>>
>> Are there any fast ways to achieve this in mnesia?
> 
>     QH = qlc:q([R#foo.id || 
>                      R <- mnesia:table(T),
>                      R#foo.foo_field =:= bar, 
>                      R#foo.user_name =:= 'Alice']),
>     lists:max([0 | qlc:e(QH)]) % assumption: 'id' is an integer > 0
> 
> If 'foo_field' or 'user_name' is the key column, or either of them is
> indexed, the query is just a lookup. Otherwise the whole table will be
> traversed, possibly using select and a match specification.
> 
> Best regards,
> 
> Hans Bolinder, Erlang/OTP
> 


Thanks a lot - this one was really useful.

-- 
Gaspar Chilingarov

System Administrator,
Network security consulting

t +37493 419763 (mob)
i 63174784
e nm@REDACTED



More information about the erlang-questions mailing list