我想这样做:
stdin
此请求在历史记录中搜索某些法规的修改日期,减去它,并以小时为单位返回差异。 如果没有找到任何行,则应将其替换为0。
它有效,但我们都可以看到它是多么丑陋。
有没有办法美化我的查询?
答案 0 :(得分:4)
一个简化:
case when X is null
then Y
else X
end
可以写成:
coalesce(X, Y)
这会将您的查询减少为:
SELECT (
EXTRACT(epoch FROM
coalesce((select date from history where statut='X' and id=6 order by date desc limit 1), now())
-
coalesce((select date from history where statut in ('Y', 'U') and id=6 order by date desc limit 1), now())
) / 3600
)
另一种简化:
select X from T order by X desc limit 1
只是:
select max(X) from T
产量:
SELECT (
EXTRACT(epoch FROM
coalesce((select max(date) from history where statut='X' and id=6), now())
-
coalesce((select max(date) from history where statut in ('Y', 'U') and id=6), now())
) / 3600
)