自动从表中选择随机行

时间:2022-05-05 03:33:14

I'm working on a project that requires back-end service. I am using MySQL and php scripts to achieve communication with server side. I would like to add a new feature on the back-end and that is the ability to generate automatically a table with 3 'lucky' members from a table_members every day. In other words, I would like MySQL to pick 3 random rows from a table and add these rows to another table (if is possible). I understand that, I can achieve this if manually call RAND() function on that table but ... will be painful!

我正在开发一个需要后端服务的项目。我使用MySQL和PHP脚本来实现与服务器端的通信。我想在后端添加一个新功能,即能够每天从table_members自动生成一个包含3个“幸运”成员的表。换句话说,我希望MySQL从表中选择3个随机行,并将这些行添加到另一个表中(如果可能的话)。我明白,如果手动调用该表上的RAND()函数,我可以实现这一点但是......会很痛苦!

There is any way to achieve the above?

有什么办法可以实现上述目标?

UPDATE:

Here is my solution on this after comments/suggestions from other users

在得到其他用户的评论/建议之后,这是我的解决方案

CREATE EVENT `draw` ON SCHEDULE EVERY 1 DAY STARTS '2013-02-13 10:00:00' ON COMPLETION NOT PRESERVE ENABLE DO 
INSERT INTO tbl_lucky(`field_1`) 
SELECT u_name 
FROM tbl_members 
ORDER BY RAND() 
LIMIT 3

I hope this is helpful and to others.

我希望这对其他人有帮助。

1 个解决方案

#1


1  

You can use the INSERT ... SELECT and select 3 rows ORDER BY RAND() with LIMIT 3

您可以使用INSERT ... SELECT并选择3行ORDER BY RAND()和LIMIT 3

For more information about the INSERT ... SELECT statement - see

有关INSERT ... SELECT语句的更多信息 - 请参阅

It's also possible to automate this every day job with MySQL Events(available since 5.1.6)

使用MySQL事件(从5.1.6开始提供)也可以自动执行每日作业

#1


1  

You can use the INSERT ... SELECT and select 3 rows ORDER BY RAND() with LIMIT 3

您可以使用INSERT ... SELECT并选择3行ORDER BY RAND()和LIMIT 3

For more information about the INSERT ... SELECT statement - see

有关INSERT ... SELECT语句的更多信息 - 请参阅

It's also possible to automate this every day job with MySQL Events(available since 5.1.6)

使用MySQL事件(从5.1.6开始提供)也可以自动执行每日作业