android 在领域表中选择一个随机行

k7fdbhmy  于 2022-12-31  发布在  Android
关注(0)|答案(5)|浏览(117)

我想从领域表中随机选择一行。类似于-

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

9rygscc11#

像这样的就行了,对吧?

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

jhdbpxl92#

取决于您要执行的操作:
您想从表中获取随机行吗?还是从随机表中获取A(随机)行?
我猜你是指前者如果您的表中有一个id,您可以:

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

您应该在此处放置最小值和最大值,如下所示:

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

(as找到here

cx6n0qe3

cx6n0qe33#

    • SWIFT 5**

我是这样做的,效果很好:

let results      = realm.objects(MyObject.self)        // Get all the objects
let randomIndex  = Int.random(in: 0 ..< results.count) // Get a random number within the number of objects returned
let randomObject = results[randomIndex]                // Get a random object
myzjeezk

myzjeezk4#

这是我在.NET中的做法,7万个条目需要7毫秒。

public IEnumerable<Entry> GetRandomEntries()
    {
        var randomizer = new Random();
        var entries = GetRealmInstance().All<Entry>().AsEnumerable();
        // Takes random entries and shuffles them to break the natural order
        var randomEntries = entries
            .OrderBy(x => randomizer.Next(0, DbQueryRandomEntriesLimit))
            .Take(DbQueryRandomEntriesLimit)
            .OrderBy(entry => entry.GetHashCode());

        return randomEntries;
    }

我使用AsEnumerable()来允许在LINQ中使用.Select

2uluyalo

2uluyalo5#

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);

假设您有一个扩展SQLiteOpenHelper的类DatabaseHelper,它就可以工作

相关问题