博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
015 有趣的查询条件
阅读量:7049 次
发布时间:2019-06-28

本文共 1517 字,大约阅读时间需要 5 分钟。

Fun with Find Conditions

You can pass more than simple strings to find conditions. Arrays, ranges, and nil values can be passed as well. In this episode you will see the tricks involved with passing these odd objects to find conditions. (Update: audio fixed).
 
你可以传递复杂的查询条件。数组,区间和空值都可以作为查询条件。这节,你会看到利用这些东西作为查询条件的情况。
 
首先,来看看
#1
>>Task.count(:all, :conditions=>["complete=? and priority=? ", false, 3])
SQL:
SELECT count(*) AS count_all FROM tasks WHERE (complete=0 and priority=3)
=>2
#2
>>Task.count(:all, :conditions=>["complete=? and priority=? ", false, nil])
SQL:
SELECT count(*) AS count_all FROM tasks WHERE (complete=0 and priority=NULL)
=>0
 
在SQL中应该是IS NULL而不是=NULL
所以
>>Task.count(:all, :conditions=>["complete=? and priority IS ? ", false, nil])
 
在查询中也可以用到数组:
 
>>Task.count(:all, :conditions=>["complete=? and priority in ? ", false, [1,3]])
SQL:
SELECT count(*) AS count_all FROM tasks WHERE (complete=0 and priority IN (1,3))
=>3
 
也可以使用区间:
 
>>Task.count(:all, :conditions=>["complete=? and priority in ? ", false, 1...3])
SQL:
SELECT count(*) AS count_all FROM tasks WHERE (complete=0 and priority IN (0,1,2))
=>3
 
在rails1.2版本中,支持conditions适用hash:
 
>>Task.count(:all, :conditions=>{:complete=>false, :priority=>1})
=>1
 
>>Task.count(:all, :conditions=>{:complete=>false, :priority=>nil})
=>0
 
>>Task.count(:all, :conditions=>{:complete=>false, :priority=>[1,3]})
=>3
 
 
>>Task.count(:all, :conditions=>{:complete=>false, :priority=>1...3})
=>3
 
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/131625,如需转载请自行联系原作者
你可能感兴趣的文章
IE, FireFox, Opera 浏览器支持CSS实现Alpha半透明的方法
查看>>
bootstrap 智能表单 demo示例
查看>>
生成器函数进阶
查看>>
spring中InitializingBean接口使用理解(转)
查看>>
js作用域和作用域链
查看>>
NX签名//NXOpen VB.Net / C# Sign
查看>>
Mac下安装nginx
查看>>
Python菜鸟之路:Django 路由补充1:FBV和CBV - 补充2:url默认参数
查看>>
【转】生活感悟
查看>>
smarty练习: 设置试题及打印试卷
查看>>
maven 项目打包配置(build节点)
查看>>
保存指定品质的图片
查看>>
多目标跟踪baseline methods
查看>>
关于QT_Creator不能在线调试问题
查看>>
六、python小功能记录——递归删除bin和obj内文件
查看>>
阅读《移山之道》及讲义感想
查看>>
python进阶-面向对象编程五:类的内置方法
查看>>
JAVA入门到精通-第52讲-面试题讲评
查看>>
05-spark streaming & kafka
查看>>
python杂记
查看>>