简体   繁体   中英

how to get next record with same last name

I am trying to retrieve the next or previous record from sqlite based on the last name field in alphabetical (asc or desc) order from my data base. However, the last name is not an unique field and also I only can retrieve one record (LIMIT 1) for every query as I am using the call back mechanism of sqlite and I don't want to buffer the results for every possible result returned from the query (unless there is no other option). I also have a unique field called customerId (ie the row id).

This is the statement that I currently use:

stream << "select * from customerTable where LastName >= '" << customerLastName << "' order by LastName asc limit 1";

I tried some other statements such as:

stream << "select * from customerTable where LastName >= '" << customerLastName << "' and CustomerId != " << customerId << " order by LastName asc limit 1";

But this one keeps flipping between 2 records with the same last name.

So I need to find a trick that would give me the next (or previous record) regardless when the last name is the same or not.

A far easier way to get all the unique names is by using SELECT DISTINCT :

select distinct LastName from customerTable order by LastName asc

That'll give you all the unique names in alphabetical order.

If you insist on using queries with limit 1 and you still want do query all records with the same last name one after the other, then you can proceed with your second approach, even though it's kind of weird. After you queried the second record with and CustomerId != you would have to query the next one with and CustomerId not in (firstId, secondId) and so on.

However, you really shouldn't go that way. The clean way is to prepare a statement first (also use host variables instead of string concatenation!) and then call sqlite_step() until you retrieved all your records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM