snippetMinor
How to join two tables with different numbers of rows
Viewed 0 times
rowstableswithnumbersjoindifferenttwohow
Problem
I've already search the net about this but it can't solve my problem.
I have two tables one with 10 rows and other with 9 rows
table 1
table 2
I want to join these two tables but I want the output to be like this
my first code is
but the result of my code is
```
RNUM JOB_ID RNUM JOB_ID
---------- ---------- ---------- ----------
1 AC_ACCOUNT 1 AC_ACCOUNT
2 AC_MGR 2 AC_MGR
3 AD_ASST 3 AD_ASST
4 AD_PRES 4 AD_PRES
5 AD_VP 5 AD_VP
6 FI_ACCOUNT 6 FI_ACCOUNT
7 FI_MGR 7 FI_MGR
8 HR_REP 8 HR_REP
9 IT_PROG 9
I have two tables one with 10 rows and other with 9 rows
table 1
RNUM JOB_ID
---------- ----------
1 AC_ACCOUNT
2 AC_MGR
3 AD_ASST
4 AD_PRES
5 AD_VP
6 FI_ACCOUNT
7 FI_MGR
8 HR_REP
9 IT_PROG
10 MK_MANtable 2
RNUM JOB_ID
---------- ----------
1 AC_ACCOUNT
2 AC_MGR
3 AD_ASST
4 AD_PRES
5 AD_VP
6 FI_ACCOUNT
7 FI_MGR
8 HR_REP
9 IT_PROGI want to join these two tables but I want the output to be like this
RNUM JOB_ID RNUM JOB_ID
---------- ---------- ---------- ----------
1 AC_ACCOUNT null null
2 AC_MGR 1 AC_ACCOUNT
3 AD_ASST 2 AC_MGR
4 AD_PRES 3 AD_ASST
5 AD_VP 4 AD_PRES
6 FI_ACCOUNT 5 AD_VP
7 FI_MGR 6 FI_ACCOUNT
8 HR_REP 7 FI_MGR
9 IT_PROG 8 HR_REP
10 MK_MAN 9 IT_PROGmy first code is
select a.*, b.*
from samp a, samp2 b where a.rnum = b.rnum(+)but the result of my code is
```
RNUM JOB_ID RNUM JOB_ID
---------- ---------- ---------- ----------
1 AC_ACCOUNT 1 AC_ACCOUNT
2 AC_MGR 2 AC_MGR
3 AD_ASST 3 AD_ASST
4 AD_PRES 4 AD_PRES
5 AD_VP 5 AD_VP
6 FI_ACCOUNT 6 FI_ACCOUNT
7 FI_MGR 7 FI_MGR
8 HR_REP 8 HR_REP
9 IT_PROG 9
Solution
When joining you join one key to another x=y but you seem to want to join x=y-1 instead. In your case you want to join 1 with 0 and 2 with 1. This is not a good practice. When joining you always you should join keys with eachother without chaning them.
You should think about what you really want as a result because it is not a logical join to do. But to genereate the result you want you can do like this:
DB Fiddle
This is a good reference image for future use:
You should think about what you really want as a result because it is not a logical join to do. But to genereate the result you want you can do like this:
select a.*, b.* from t1 a LEFT OUTER JOIN t2 b on a.rnum-1 = b.rnumDB Fiddle
This is a good reference image for future use:
Code Snippets
select a.*, b.* from t1 a LEFT OUTER JOIN t2 b on a.rnum-1 = b.rnumContext
StackExchange Database Administrators Q#183359, answer score: 2
Revisions (0)
No revisions yet.