douqian2334 2015-06-03 08:50
浏览 120
已采纳

如何在使用INNER JOIN时让MySQL选择随机获胜者

SELECT * FROM `surveys` INNER JOIN `surveyusers` ON `surveyusers`.`survID` = `surveys`.`survID` WHERE `surveyusers`.`hasWon` = 0 ORDER BY RAND();
UPDATE surveys SET winner = email;

This was a school assignment that required us to select and update the survey winner.

I use PHP to manage and show surveys, I want the SQL to pick the winner. PHP sets survID

I want to pick a random winner and set the winner coloumn in surveys table to the email in the surveyusers table. But I really have a lot of trouble with it.

  • 写回答

2条回答 默认 最新

  • douzhanrun0497 2015-06-03 09:00
    关注

    Updates can take the same syntax as a Select.

    You can combine these two queries into one.

    UPDATE `surveys` `s` SET `s`.`winner` = (
        SELECT email FROM `surveyusers`
        WHERE `surveyusers`.`hasWon` = 0
        AND `survID` = 1
        ORDER BY RAND()
        LIMIT 1
    ) WHERE `survID` = 1;
    

    The survID you would have to set from PHP of course.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度