Select a Random row in realm table

ⅰ亾dé卋堺 提交于 2019-12-23 16:08:22

问题


I want to select a random row from the realm table. Something like -

SELECT * FROM table ORDER BY RANDOM() LIMIT 1;

回答1:


Something like this would do, yes?

Random random = new Random();
RealmResults<YourTable> list = realm.where(YourTable.class).findAll();
YourTable yourTable = list.get(random.nextInt(list.size()));



回答2:


Depends on what you want to do:

Do you want to get a random row from a table? Or A (random) row from a random table?

I guess you mean the former: If you have an id in your table, you could just:

SELECT * FROM table b WHERE id = FLOOR(RAND() * (3 - 0 + 1)) + 0

You should place a min and max here like so:

FLOOR(RAND() * (<max> - <min> + 1)) + <min>

(as found here)




回答3:


String query =String.format("SELECT * FROM realm ORDER BY %d LIMIT 1", random());
databaseHelper = new DatabaseHelper(this);
        database = databaseHelper.getWritableDatabase();
Cursor cursor = database.execSQL(query);

It works assuming that you have a class DatabaseHelper which extends SQLiteOpenHelper



来源:https://stackoverflow.com/questions/33827910/select-a-random-row-in-realm-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!