我有以下表格:
表1:
+-----------+-------------+
| record_id | record_name |
+-----------+-------------+
| 0 | 'test' |
| 1 | 'test1' |
| 5 | 'mytest' |
| 8 | 'ultratest' |
| .... | .... |
+-----------+-------------+
表2:
+---------+-----------+
| user_id | record_id |
+---------+-----------+
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| .... | .... |
+---------+-----------+
我想为表2的每一行分配来自id的随机record_id,存在于表1(0,1,5,8)中; ids不一定是唯一的。
我已阅读this answer,这种情况并不好,因为那里分配的数字是顺序的
我如何使用mysql做到这一点?
答案 0 :(得分:0)
来自mysql文档
要获取R
范围内的随机整数i <= R < j
,请使用表达式FLOOR(i + RAND() * (j – i))
。例如,要获取范围7 <= R < 12
范围内的随机整数,可以使用以下语句:
SELECT FLOOR(7 + (RAND() * 5));
答案 1 :(得分:0)
select t2.user_id, t1.record_id
from
t2
inner join (
select record_id
from t1
order by rand()
) t1 on 1 = 1
group by t2.user_id