2015-05-27 50 views
1

我有4個表:T1,T2,T3,T4如何在postgresql中加入2個子查詢?

--T1:    
    Info_Id | fname | lname 
    101  | rol | lum 

--T2: 
    Acc_id | acc_info_id | acc_property 
    01  | 101   | land  

--T3: 
    Bill_id | status | amt_2_paid | Acc_id 
    123  | UNPAID | 200  | 01 

--T4: 
    Accnt_bill | OR  | Acc_id 
    123  || 01 

我有兩個子查詢,如下圖所示:

SELECT 
     fname, 
     lname 
    FROM T1 
WHERE Info_id IN(SELECT Acc_id FROM T2 WHERE acc_info_id = '') 

第一子查詢只顯示fnamelname

SELECT 
     status, 
     amt_2_paid 
FROM T3 
WHERE Bill_id IN(SELECT Accnt_id FROM t4 WHERE OR = '') 

第二個子查詢僅顯示statusamt_2_paid

我的問題是如何加入兩個子查詢,以顯示值fname,name,statusamt_2_paid當我輸入OR號。

+2

請指定您正在使用的RDBMS。 – Rigel1121

+0

也請說明字段的相關性,因爲命名是一團糟。下一次,請**發佈匹配您的sql查詢的表格模式。表格描述中的列與查詢中的名稱不匹配。這只是馬虎。 –

+0

SELECT t1,fname,t1.lname,t3.status,t3.amt_2_paid FROM t1 INNER JOIN T2 on t1.info_id = t2.acc_info_id INNER JOIN T3 on t2.acc_id = t3.acc_id –

回答

2

只需將您的所有表使用INNER JOIN一個查詢。見下:

SELECT 
     T1.fname, 
     T1.lname, 
     T3.status, 
     T3.amt_2_paid 
FROM T1 
INNER JOIN T2 ON T1.Info_id=T2.acc_info_id 
INNER JOIN T3 ON T2.Acc_id=T3.Acc_id 
INNER JOIN T4 ON T3. Bill_id=T4.Accnt_bill 
WHERE T4.[OR] ='' 
0
SELECT fname, name, status,amt_2_paid 
FROM T3 
INNER JOIN t4 ON t3.Bill_id = t4.Accnt_bill 
INNER JOIN t2 ON t2.Acc_id = t3.Acc_id 
INNER JOIN t1 ON t1.Info_id = t2.Info_Id 
WHERE t4."OR" = '' 
0
SELECT 
    t1.fname, 
    t1.lname, 
    t3.status, 
    t3.amt_2_paid 
FROM 
    t1 
    INNER JOIN t2 on t1.info_id = t2.acc_info_id 
    INNER JOIN t3 on t2.acc_id = t3.acc_id 
    INNER JOIN t4 on t3.bill_id = t4.accnt_bill 
WHERE 
    t4.[or] = ''