Unir dos tablas con diferentes valores clave
Frecuentes
Visto 57 equipos
1
Tengo dos mesas:
tabla 1
Name | AMOUNT | TYPE
John | 20 | TH
Jill | 10 | IU
Bill | 30 | IK
John | 45 | AL
Tabla 2
TYPE | DESC
88 | RENT
34 | ALIMONY
87 | TAX
56 | BEER
I have to join these tables. I know that TYPE 'TH'
in table 1 corresponds to '88' in table 2.
Similarly, IK corresponds to 87 and so on . But there isn't any reference table which says so which I could use for joining these . Is there any workaround for this ?
4 Respuestas
0
If these are the only data contained on the tables you can create a new table, table3
:
TYPE 1| TYPE2
88 | TH
34 | IU
87 | IK
56 | AL
Y prueba:
select Name,Amount,Type.table1,Type,table2 from table1 inner join table3
on table1.Type=table3.Type2
inner join
table2 on table2.type=tabl3.type1
contestado el 28 de mayo de 14 a las 14:05
0
You don't mention DBMS but you should be able to use a derived table like:
select ...
from t1
join ( values ('TH',88),('IK',87) ) as a (x,y)
on t1.type = a.x
join t2
on a.y = t2.type
Es posible que tengas que hacer algo como:
join ( select ('TH',88) union all select ('IK',87) ) as a (x,y)
instead. But if this relationship exists, why don't create a table for it and insert the information?
contestado el 28 de mayo de 14 a las 14:05
0
Ok, this is a rather strange question because it is against the rules of relational databases. But you can fix it like this:
inner join Table2 on Table2.Type = 88 and Table1.Type = 'TH'
This you can do for each combination. But I suggest it would be better to add a new column with a reference to the id of the type.
contestado el 28 de mayo de 14 a las 14:05
0
If there exists some good reason for not creating a third table, you can write something like:
SELECT
........
FROM
table1 a
JOIN table2 b
ON
(
CASE
WHEN a.type='TH'
THEN 88
WHEN a.type='IK'
THEN 87
...........
END
)
=b.type
contestado el 28 de mayo de 14 a las 15:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas sql key inner-join openquery or haz tu propia pregunta.
Create a table with rows TH 88, IK 87 etc, if there isn't already one, and use two joins. - i-blis