V
V
Vlad Sklyarenko2016-02-07 11:53:03
PHP
Vlad Sklyarenko, 2016-02-07 11:53:03

Is it possible to combine these two sql queries into one?

Is it possible to combine these two queries into one. The point is to select a random entry that has correct<2. Thank you in advance. Perhaps there is another solution. ORDER BY RANDOM() doesn't seem to work well for me.

$sql = "CREATE TEMP TABLE result(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,realId,rus,eng);INSERT INTO result(realId,rus,eng) SELECT id,rus,eng FROM words WHERE correct<2;";
  $db->exec($sql);
  $sql = "SELECT realId as id,rus,eng FROM result WHERE id = (ROUND(ABS(((SELECT COUNT(*) FROM result)-1)*RANDOM()/9223372036854775807))+1);";
  $result = $db->query($sql);
  $arr = $result->fetch(PDO::FETCH_ASSOC);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2016-02-07
@NauGaika

I would theoretically do something like this:
1. We get a random number (rnd) from 1 to count (*)
2. We select records from the top rnd table with reverse sorting by ID and take the first record from the selection, direct sorting is also possible, but then we take the last record:
select top @rnd * from result order by ID desc
Didn't deal with sqlite, that's why "theoretically".

V
Vlad Sklyarenko, 2016-02-07
@NauGaika

$sql = "SELECT id,rus,eng FROM words WHERE (correct<2 AND id < (ABS(ROUND(((SELECT COUNT(*) FROM words WHERE correct < 2)-1)*RANDOM()+1)/9223372036854775807))) ORDER BY id DESC LIMIT 1;";
  $result = $db->query($sql);
  $arr = $result->fetch(PDO::FETCH_ASSOC);

Somehow it happened. But it seems to work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question