Thank you. get_recordset_sql is what I needed.
Oh wait, no it is not the answer because I get a different result from a direct SQL query in the database. It doesn't throw out the duplicates.
in your queries you can add
RAND() unid
Give something like
SELECT RAND() mainid, t1.* FROM (
....
Hope it's help.
postgress doesnt support rand() but random()
The other way more sql standard I found it's use concat.
In my case for ex :
select concat(t1.userid , t1.groupid) unid ...
If you really want that to be cross-db, use Moodle's $DB->sql_concat('t1.userid', 't1.groupid') function.
Thank you. Probably basic for you but really good info for me