0

我有一个名为 users 的数据库表(25k 记录)

在里面我有一个名为“头像”的字段

我需要更新此字段,从列表中分配一个随机 url

列表网址:

http://myserver.com/img/1.png
http://myserver.com/img/2.png
http://myserver.com/img/3.png
http://myserver.com/img/4.png
http://myserver.com/img/5.png
http://myserver.com/img/6.png
http://myserver.com/img/7.png
http://myserver.com/img/8.png
http://myserver.com/img/9.png
http://myserver.com/img/10.png
http://myserver.com/img/11.png
http://myserver.com/img/12.png
http://myserver.com/img/13.png
http://myserver.com/img/14.png
http://myserver.com/img/15.png

我有这个代码:

UPDATE TABLE SET VALUE=VALUE+ROUND(1+RAND()*4);

我该如何调整这个查询?

4

2 回答 2

1

如果您的图像遵循良好的模式,@peterm 的答案很好,但您也可以从列表中选择一个随机字符串:

SELECT ELT(ROUND(0.5+RAND()*15), 
 'http://myserver.com/img/1.png',
 'http://myserver.com/img/2.png',
 'http://myserver.com/img/3.png',
 'http://myserver.com/img/4.png',
 'http://myserver.com/img/5.png',
 'http://myserver.com/img/6.png',
 'http://myserver.com/img/7.png',
 'http://myserver.com/img/8.png',
 'http://myserver.com/img/9.png',
 'http://myserver.com/img/10.png',
 'http://myserver.com/img/11.png',
 'http://myserver.com/img/12.png',
 'http://myserver.com/img/13.png',
 'http://myserver.com/img/14.png',
 'http://myserver.com/img/15.png') AS avatar;

http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_elt

要更新表,您可以ELT()在 UPDATE 语句中使用相同的表达式:

UPDATE TABLE SET AVATAR=ELT(...);
于 2013-10-21T18:43:08.080 回答
0

你在寻找这样的东西吗?

UPDATE users
   SET avatar = CONCAT('http://myserver.com/img/', FLOOR(1 + RAND() * 15), '.png');

这是SQLFiddle演示


虽然我建议只存储整数部分,但如果你需要存储它,

UPDATE users
   SET avatar = FLOOR(1 + RAND() * 15);

SELECT id, CONCAT('http://myserver.com/img/', avatar, '.png') avatar
  FROM users;

这是SQLFiddle演示

然后在您选择数据时即时构建一个头像网址,或者更好的是在您的客户端代码中执行此操作(从某种设置中获取域名和路径)

SELECT id, CONCAT('http://myserver.com/img/', FLOOR(1 + RAND() * 15), '.png') avatar
  FROM users;

这是SQLFiddle演示

于 2013-10-21T18:40:32.063 回答