我有一个名为users(25k记录)的数据库表
我有一个名为“阿凡达”的字段
我需要更新此字段,从列表中分配一个随机网址
列出网址:
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);
我该如何调整此查询?
答案 0 :(得分:1)
如果您的图片遵循漂亮的图案,@ itterm的答案很好,但您也可以从列表中选择一个随机字符串:
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
要更新表,可以在UPDATE语句中使用相同的ELT()
表达式:
UPDATE TABLE SET AVATAR=ELT(...);
答案 1 :(得分: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 演示