سؤال

I try to get select from two tables and put some data from one to other with ussing WHERE (PL/SQL)

I have two tables like those:

table1

ID  NAME  COLOR  COMPANY_SHORT_NR
1   a     Green  1
2   b     Red    23
3   c     Blue   null
4   a     Green  null
5   g     Green  1

table2

ID  SHORT COMP_NAME
1   1     company_name_1 
2   23    comapny_name_2

and now I would like to get all data from table 1 with companies names and if its null get info it is null like that

1   a     Green  company_name_1 
2   b     Red    comapny_name_2 
3   c     Blue   null
4   a     Green  null
5   g     Green  company_name_1 

I tried do it like this:

select ID
      ,NAME
      ,COLOR
      ,COMPANY_SHORT_NR
from table1
    ,table2
where COMPANY_SHORT_NR = SHORT 

but this give me only not null values:

1   a     Green  company_name_1 
2   b     Red    comapny_name_2 
5   g     Green  company_name_1 

if i use sth like this:

select ID
      ,NAME
      ,COLOR
      ,COMPANY_SHORT_NR
from table1
    ,table2
where COMPANY_SHORT_NR = SHORT or COMPANY_SHORT_NR is null

I get thousends of records ... If I use only IS NULL than it returns me only 2 rows as it should be.

Where I make mistake ?

هل كانت مفيدة؟

المحلول 2

you neen OUTER JOIN for that

select ID
      ,NAME
      ,COLOR
      ,COMPANY_SHORT_NR
from table1
     LEFT OUTER JOIN table2 ON ( COMPANY_SHORT_NR = SHORT )

نصائح أخرى

You have to use left join as below

select ID
      ,NAME
      ,COLOR
      ,COMPANY_SHORT_NR
from table1 t1
left join table2 T2 on t1.COMPANY_SHORT_NR = t2.SHORT 

wouldn't it be better to join the tables? like SELECT ID, NAME, COLOR, COMPANY_SHORT_NR FROM table1 t1 LEFT JOIN table2 t2 on t2.SHORT = t1.COMPANY_SHORT_NR WHERE 1

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top