选择一列然后再次随机插入该列

时间:2016-02-04 19:35:24

标签: mysql sql random

我有一张桌子:

player_id|player_name|play_with_id|play_with_name|

我为游戏制作了这张桌子。

每个想玩的人都可以注册。

当他们注册表存储player_idplayer_name

当他们可以注册的时间段过期时,我想随机将player_name分配给play_with_name

所以例如..我的结构在注册期间会喜欢这个:

player_id|player_name|play_with_id|play_with_name|
1          someone1
2          someone2
3          someone3
4          someone4
5          someone5

这段时间到期了:

player_id|player_name|play_with_id|play_with_name|

    1       someone1      2              someone2
    2       someone2      1              someone1
    3       someone3      4              someone4
    4       someone4      3              someone3
    5       someone5      -                 -

2 个答案:

答案 0 :(得分:2)

我无法测试这个,因为我没有方便的MySQL数据库,而SQLFiddle似乎永远需要运行任何东西,但这有希望让你在那里或至少关闭:

SET @row_num = 0;
SET @last_player_id = 0;

UPDATE P
SET
    play_with_id =
        CASE
            WHEN P.player_id = SQ.player_id THEN SQ.last_player_id
            ELSE player_id
        END
FROM
    Players P
LEFT OUTER JOIN
(
    SELECT
        @row_num := @row_num + 1 row_num,
        @last_player_id last_player_id,
        @last_player_id := player_id player_id
    FROM
        Players
    WHERE
        MOD(@row_num, 2) = 0
    ORDER BY
        RAND()
) SQ ON SQ.player_id = P.player_id OR SQ.last_player_id = P.player_id

代码(希望)随机对玩家进行排序,然后根据该顺序对其进行配对。随机排序结果中的每个其他玩家都与之前的人配对。

在MS SQL Server中RAND()只会在此处评估一次,并且最终不会影响ORDER BY,但我认为 MySQL会处理RAND()不同,并为结果集中的每一行生成一个新值。

答案 1 :(得分:0)

我不确定为什么有些客户端代码没有这样做而不是在数据库级别完成此操作,但我想如果你得到了基于检索随机行集的策略你的数据库来自here,然后你可以用游标或迭代器编写一个存储过程来遍历结果集,如:

select player_id, player_name from players order by RAND()

然后遍历所有表行以更新play_with_id和play_with_name,其中先前选择的player_id<> play_with_id。