如何缩短多次使用相同表达式的 PostgreSQL 查询?



我想缩短这个postgresql查询,这样我就不需要多次重复"coalesce(gl.email,mc.email"...

select r.*,l.*, coalesce(r.email, l.email) 
from righttable r full outer join  lefttable l on r.email=l.email 
where coalesce(r.email, l.email) > 'h' 
order by coalesce(r.email, l.email) limit 10

您可以使用using子句连接:

select *
from righttable r 
full outer join  lefttable l using(email)
where email > 'h' 
order by email 
limit 10

从文档中:

USING子句是一种简写,允许您利用联接两端对联接列使用相同的名称的特定情况。

此外,JOIN USING的输出抑制冗余列:无需打印两个匹配的列,因为它们必须具有相等的值。虽然JOIN ON生成T1中的所有列,后跟T2中的所有列,JOIN USING为每个列出的列对生成一个输出列(按列出的顺序(,然后是T1中的任何剩余列,后跟T2中的任何剩余列。

这是对我有用的解决方案...

我连续重复此选择查询。

select r.<field1>, r.<field2>, ..., l.<field1>, l.<field2>,...,coalesce(r.email, l.email) from righttable r full outer join  lefttable l on r.email=l.email where coalesce(r.email, l.email) > <last_read_email_address> order by coalesce(r.email, l.email) limit 10

在每个连续的请求中,我将 last_read_email_address 的值设置为上一个结果集中的最终合并电子邮件地址。

简单。

最新更新