postgresql JOIN有多个条件

时间:2017-09-27 15:54:39

标签: sql postgresql

我有两张postgres表:

worker_details_verification (verification_id BIGSERIAL, worker_id BIGINT, 
state TEXT, proofs TEXT[])
worker_details(worker_id BIGINT, name TEXT)

现在我想得到

    `verification_id, worker_id, proofs FROM` the table 
    `worker_details_verification`  

限制记录`WHERE state ='Initial'

现在除了以上三列之外,我还想要worker_details表中的名称列,其中worker_id可用于查询工作人员的姓名。

我尝试了以下查询,但它无效。

SELECT a.verification_id, a.worker_id, a.state, a.proofs, b.Name FROM 
worker_details_verification a FULL OUTER JOIN worker_details b ON 
a.worker_id = b.worker_id AND a.state = 'Initial';

它会返回即使a.state不是'Initial'的记录,也会返回一些错误记录,其中name的所有worker_detail都返回NULL worker_details_verification列。

2 个答案:

答案 0 :(得分:1)

听起来我不是一个Full Outer Join,而是你想要一个Left / Right,因为你正在寻找来自Worker_Details_Verification的数据,然后过滤它,同时在适用的时候抓住Worker_Details。

我接受了这个:

SELECT a.verification_id, a.worker_id, a.state, a.proofs, b.Name 
FROM worker_details_verification a 
     FULL OUTER JOIN worker_details b ON a.worker_id = b.worker_id AND a.state = 'Initial';

进入这个:

SELECT a.verification_id, a.worker_id, a.state, a.proofs, b.Name 
FROM worker_details_verification a 
     LEFT OUTER JOIN worker_details b ON a.worker_id = b.worker_id 
WHERE a.state = 'Initial';

答案 1 :(得分:0)

你试过这样的吗?

SELECT a.verification_id, a.worker_id, a.state, a.proofs, b.Name 
FROM worker_details_verification a 
INNER JOIN worker_details b ON a.worker_id = b.worker_id
WHERE a.state = 'Initial';