Ruby Sequel是否具有SQL“coalesce”功能的等效功能?

时间:2013-08-05 13:59:03

标签: sequel coalesce

在SQL中为了避免获得NULL值,我可以使用“coalesce”函数来代替它:

SELECT COALESCE(some_column, 0) FROM some_table;  

但我找不到用Sequel做同样事情的方法。

2 个答案:

答案 0 :(得分:6)

DB[:some_table].select{coalesce(some_column, 0)}

答案 1 :(得分:1)

另一种语法版本是Sequel.function(:coalesce,:some_column,5)

示例:

require 'sequel'
Sequel.extension :pretty_table    
DB = Sequel.sqlite
DB.create_table(:mytables){
  primary_key :id
  field :a, :type => :nvarchar, :size => 10
  field :some_column, :type => :fixnum
}

DB[:mytables].insert(:a => 'a1', :some_column => 10)
DB[:mytables].insert(:a => 'a2')

Sequel::PrettyTable.print(
  DB[:mytables].select(:a, :some_column, Sequel.function(:coalesce,:some_column,5))
)

结果:

+--+--------------------------+-----------+
|a |coalesce(`some_column`, 5)|some_column|
+--+--------------------------+-----------+
|a1|                        10|         10|
|a2|                         5|           |
+--+--------------------------+-----------+