duanli12176 2012-11-20 20:39
浏览 76
已采纳

SQL查询使用通过随机选择另一个表中的值来替换一个表中的值

I have a table with an value that I would like to be updated periodically with a cron job. However, I need to update the value by replacing it with a value from a different table. The issue is that I would like the replacement value to be chosen randomly.

For example, Table 1 has

ID    Email
=================
1     bobatumail

Table 2 has:

ID    Email
================
1     bobatumail
2     joeatumail
3     peteatumail
4     biffatumail
5     wilneratumail
6     wilsonatumail

I would like the query to replace bobatumail in Table 1 with any of the other values in Table 2 as long as it is random. It could even be the same value as in Table 1.

Any idea how to do this?

  • 写回答

1条回答 默认 最新

  • dsjz1119 2012-11-20 21:21
    关注

    In MySQL you could use the REPLACE statement:

    REPLACE INTO table1 (ID, Email)
    SELECT 1, table2.Email FROM table2 ORDER BY RAND() LIMIT 1;
    

    The "1" in the second line represents the id of the entry while the second part returns a random value out of table2. Yes, there are solutions using the UPDATE statement (JOIN and ANSI) but its always tricky and you usually have to turn off safe update mode.

    http://dev.mysql.com/doc/refman/5.5/en/mysql-command-options.html#option_mysql_safe-updates

    Please note that REPLACE first deletes the old entry and then reinserts the new one.

    http://dev.mysql.com/doc/refman/5.5/en/replace.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题