优化连接查询

时间:2013-07-23 11:17:42

标签: sql left-join

我有以下查询 -

select res.name, test.stringvalue 
from tr_resource res 
left outer join 
(select rch.resourceid,cv.stringvalue from tr_resourcecharac rch 
inner join tr_characvalue cv on rch.characvalueid = cv.characvalueid 
inner join tr_charac ch on cv.characid = ch.characid and ch.name='Security Clearance Required')test
on res.resourceid=test.resourceid
where res.resourceid=135021

我的输出低于此值 -

name stringvalue
ABC  null

我不想在左连接后使用子查询。如果有办法将这个查询写成我尝试在下面写的一系列连接,你能不能告诉我 -

select res.name,cv.stringvalue 
from tr_resource res
left outer join tr_resourcecharac rch on res.resourceid=rch.resourceid
inner join tr_characvalue cv on rch.characvalueid =cv.characvalueid
inner join tr_charac ch on ch.characid=cv.characid and ch.name='Security Clearance Required'
where res.resourceid=135021

但是这个查询没有输出。

对于表格方案,您可以参考 -

tr_resource as -

Resourceid  name
135021       ABC

tr_charac as

characid   name
1          Security Clearance Required
2          CH2

tr_characvalue as -

characvalueid characid stringvalue
cv1             1       XX
cv2             2       YY
cv3             2       zz

tr_resourcecharac as -

resourceid  characvalueid
135021          cv2

我已提出这个问题,但没有人回答。因此,请使用更多信息重新发布此问题

1 个答案:

答案 0 :(得分:0)

您可以在不将派生表格重写为

的情况下重写查询
SELECT res.name,
       cv.stringvalue
FROM   tr_resource res
       LEFT OUTER JOIN tr_resourcecharac rch
                       INNER JOIN tr_characvalue cv
                         ON rch.characvalueid = cv.characvalueid
                       INNER JOIN tr_charac ch
                         ON cv.characid = ch.characid
                            AND ch.name = 'Security Clearance Required'
         ON res.resourceid = test.resourceid
WHERE  res.resourceid = 135021 

我怀疑这将是一个优化。它只是表达同样事物的另一种方式。

或另一种方式是

SELECT res.name,
       cv.stringvalue
FROM   tr_resourcecharac rch
       INNER JOIN tr_characvalue cv
         ON rch.characvalueid = cv.characvalueid
       INNER JOIN tr_charac ch
         ON cv.characid = ch.characid
            AND ch.name = 'Security Clearance Required'
       RIGHT OUTER JOIN tr_resource res
         ON res.resourceid = test.resourceid
WHERE  res.resourceid = 135021