2013-05-15 24 views
0

我有這樣一個SQL語句:變換SELECT statememnt加入

SELECT a.status_id, 
     (SELECT batch_name 
     FROM pf_req_batch 
     WHERE batch_id = (SELECT batch_id 
          FROM pf_m_req_batch 
          WHERE request_id = 282)) AS BATCH_NAME 
FROM pf_request 
WHERE request_id = 282; 

我需要使用JOIN來改變它。幫助,PLZ!

+1

不確定你的意思是...你需要加入2張桌子嗎? – DiederikEEn

回答

0

你可以試試這個:

SELECT R.STATUS_ID, B.BATCH_NAME 
FROM PF_REQUEST R 
INNER JOIN PF_REQ_BATCH B ON B.BATCH_ID = R.PF_M_REQ_BATCH.BATCH_ID 
WHERE REQUEST_ID=282; 
0
SELECT PR.STATUS_ID, PRB.BATCH_NAME as BATCH_NAME 
     FROM PF_REQ_BATCH PRB, PF_M_REQ_BATCH PMRB,PF_REQUEST PR 
     WHERE PRB.BATCH_ID = PMRB.BATCH_ID 
     AND PMRB.REQUEST_ID = PR.REQUEST_ID 
     AND PR.REQUEST_ID=282; 
0
SELECT A.STATUS_ID, b.BATCH_NAME 
FROM PF_REQUEST A inner join PF_REQ_BATCH as b 
on A.Batch_ID = b.Batch_Id 
    WHERE A.REQUEST_ID=282; 
0

您有涉及三個表。但是,您似乎並不需要pf_req_batch,因爲request_idpf_requestpf_m_req_batch中。

此代碼在pf_m_req_batch表中查找batch_name。這裏有一種方法來做連接:

select r.status_id 
from pf_request r left outer join 
    pf_req_batch rb 
    on r.request_id = rb.request_id 
where r.request_id = 282; 

請注意使用left outer join。原始數據保留來自pf_request的所有匹配記錄。這個結構可能會產生重複的結果(如果在pf_m_req_batch中有多個匹配的行,但是根據你原來的查詢,這不應該發生在你的情況中)。如果有,你會得到一個子查詢錯誤(類似於返回多行的子查詢。)

0

假設表pf_m_req_batch是結表和組合(request_id, batch_id)是唯一的,這會做:

SELECT r.status_id, 
     b.batch_name 
FROM pf_request r 
    LEFT JOIN pf_m_req_batch rb 
    ON rb.request_id = r.request_id 
    LEFT JOIN pf_req_batch b 
    ON rb.batch_id = b.batch_id 
WHERE r.request_id = 282 ; 

如果不是唯一的(這是更可能的),那麼這個查詢將顯示許多行,每個批次與請求282關聯,而您的查詢會引發錯誤。