如何使用oracle sql查询连接两个表?

时间:2015-11-26 22:41:21

标签: sql oracle

我有两张桌子:工作和鳕鱼

     jobs                                          cods

idx   descr                                    cod       descr      idx

1    teacher                                   codx      codingx     1
2    programmer                                cody      codingy     4 
3    sailor                                    codz      codingz     2
4    medic                                     codw      codingw     3
5    student                                   cods      codings     1  
                                               codw      codingw     1

我想要选择,返回带有codx和codw的行,其中idx列是连接

id    descr            codx      desc_codx     codw    descr_codw    
1     teacher          codx      codingx       codw     codingw
2     programmer       null       null         null     null     
3     sailor           null       null         codw     codingw
4     medic            null       null         null     null  
5     student          null       null         null     null 

只有1个选择是否可能?

select x.id, x.descr,a.cod as codx a.desc as desc_codx,b.cod as codw, b.desc as desc_codw 
from jobs x, cods a, cods b 
where x.id= a.id(+) 
  and x.id = b.id(+) 
  and a.cod= 'codx' 
  and b.cod= 'codw'

2 个答案:

答案 0 :(得分:2)

是的,有可能。 您需要两个连接才能执行此操作,以便为codxcodw创建单独的列。

SELECT
  j.idx, j.descr,
  c.cod AS codx, c.descr AS desc_codx,
  c2.cod AS codw, c2.descr AS desc_codw
FROM
  jobs j
  LEFT JOIN cods c ON j.idx = c.idx AND c.cod = 'codx'
  LEFT JOIN cods c2 ON j.idx = c2.idx AND c2.cod = 'codw'

您也可以仅使用1个JOIN并使用CASE语句来执行此操作。这可能看起来更像是写作,但在性能方面它要好得多,因为我们只扫描一次表cods而评估CASEs会得到更多回报。

SELECT
  j.idx, j.descr,
  CASE WHEN c.cod = 'codx' THEN c.cod END AS codx,
  CASE WHEN c.cod = 'codx' THEN c.descr END AS desc_codx
  CASE WHEN c.cod = 'codw' THEN c.cod END AS codw,
  CASE WHEN c.cod = 'codw' THEN c.descr END AS desc_codw
FROM
  jobs j
  LEFT JOIN cods c ON j.idx = c.idx AND c.cod IN ('codx', 'codw')

答案 1 :(得分:0)

select jobs.* , cods.* from jobs,cods where jobs.idx=cods.idx;