简体   繁体   English

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

[英]How to make MySQL select a random winner when using INNER JOIN

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来管理和显示调查,我希望SQL选择胜利者。 PHP sets survID PHP设置了survID

I want to pick a random winner and set the winner coloumn in surveys table to the email in the surveyusers table. 我想选择一个随机的赢家,并将调查表中的获胜者coloumn设置为surveyusers表中的电子邮件。 But I really have a lot of trouble with it. 但我真的遇到了很多麻烦。

Updates can take the same syntax as a Select. 更新可以采用与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. 你必须从PHP设置的幸存者当然。

You can nest a SELECT query within your UPDATE query: 您可以在UPDATE查询中嵌套SELECT查询:

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

where xxx is the survey to update. 其中xxx是要更新的调查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM