2015-10-22 36 views
-1

这可能是一个非常简单的问题,我在看的,但我有这个疑问:如何从表中选择行,但如果它不存在于该表中,请从不同的表中选择?

SELECT is_accountant from users where customer_id='cus_4znUZe3lAy26FT' 

(客户ID会有所不同,我使用了一个节点js脚本抢了一堆不同客户ID,以找出是否他们会计师与否)

如果没有结果,我想在一个表中搜索名为deleted_users同一客户ID,即:

SELECT is_accountant from deleted_users where customer_id='cus_4znUZe3lAy26FT' 

是否有办法在Postgresql中做到这一点?

回答

2
SELECT coalesce(u.is_accountant, d.is_accountant) 
from deleted_users d 
full outer join users u on u.id = d.id 
where 'cus_4znUZe3lAy26FT' in (d.customer_id, u.customer_id) 
1
SELECT is_accountant from users where customer_id='cus_4znUZe3lAy26FT' 

union all 

SELECT is_accountant from deleted_users where customer_id='cus_4znUZe3lAy26FT' 
and not exists 
(SELECT is_accountant from users where customer_id='cus_4znUZe3lAy26FT') 

,或者如您有兴趣知道,如果用户 “是(或曾经)” 会计师: (?它无论在哪个表用户同意?)

SELECT is_accountant from users where customer_id='cus_4znUZe3lAy26FT' 
union 
SELECT is_accountant from deleted_users where customer_id='cus_4znUZe3lAy26FT'