我有一个相当复杂的case语句在MySQL中有效:
SELECT # rest of code omitted
CASE WHEN code = 'a' THEN 'x'
WHEN code IN ('m','n') THEN 'y'
WHEN class IN ('p','q') AND amount < 0 THEN 'z'
ELSE NULL END AS status
FROM # rest of code omitted
然而,所有在续集中写这篇文章的尝试都失败了.我使用它作为模板:
Sequel.case([[:c,1],[:d,2]],0) # (CASE WHEN "c" THEN 1 WHEN "d" THEN 2 ELSE 0 END)
我最好的猜测是:
dataset.select( # rest of code omitted...
[[(:code => 'a'),'x'],[(:code => 'b'),'y'],[(:class => ['p','q'],:amount < 0),'z']].case(nil).as(:status))
有任何想法吗?
最佳答案
在玩完这个游戏之后,我得出结论,虽然续集宝石的目标是“简单,灵活和强大”,但是当事情变得有点棘手时,它的语法会变得非常复杂.
这是我对您的查询的最佳尝试:
DB[:testtable].select(
Sequel.case([
[{code: 'a'},[{code: ['m','n']},[{class: ['p',(Sequel.expr(:amount) > 0) => true},'z']],nil).
as(:status)
)
这会产生以下(几乎正确的)sql:
SELECT (
CASE WHEN (`code` = 'a') THEN 'x'
WHEN (`code` IN ('m','n')) THEN 'y'
WHEN ((`class` IN ('p','q')) AND ((`amount` > 0) IS TRUE)) THEN 'z'
ELSE NULL END) AS `status` FROM `testtable`
我无法弄清楚如何在case语句中使用不等式运算符.也许你会有更多的运气.