我有一个sql语句,如:
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!
答案 0 :(得分: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;
答案 1 :(得分: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;
答案 2 :(得分: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;
答案 3 :(得分:0)
你有三张桌子。但是,您似乎不需要pf_req_batch
,因为request_id
和pf_request
都有pf_m_req_batch
。
此代码正在查找batch_name
表中的pf_m_req_batch
。这是进行连接的一种方法:
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
中有多个匹配行。但是,根据您的原始查询,这不应该发生在您的情况下。如果确实如此,您将得到一个子查询错误(类似于子查询返回多行)。
答案 4 :(得分: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相关联,而您的查询将抛出错误。