2 mysql sqlite random ruby-on-rails
嘿伙计们,我正在尝试从Ruby on Rails中的数据库中选择随机数据.不幸的是,sqlite和mysql对"随机"函数使用不同的名称.Mysql使用rand(),sqlite使用random().到目前为止,我一直非常高兴在我的开发环境中使用sqlite,而且我不想为此付出代价.
所以我有一个解决方案,但我对此并不满意.首先,在RoR中是否有更清晰的抽象来获取随机函数?如果没有,这是获得"适配器"的最佳方式吗?
# FIXME: There has to be a better way...
adapter = Rails.configuration.database_configuration[Rails.configuration.environment]["adapter"]
if adapter == "sqlite3"
# sqllite calls it rand
random = "random"
else
# mysql calls it rand
random = "rand"
end
query.push("SELECT *, (" + random + "() * (0.1 * value)) AS weighted_random_value...")
Run Code Online (Sandbox Code Playgroud)
您可以通过创建函数有效地将MySQL的别名rand()设为标准random():
CREATE FUNCTION random() RETURNS FLOAT NO SQL SQL SECURITY INVOKER RETURN rand();
Run Code Online (Sandbox Code Playgroud)