我想缩短这个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 的值设置为上一个结果集中的最终合并电子邮件地址。
简单。