simon77
simon77

Reputation: 73

T-SQL - joining two tables without primary key

I have 2 tables that represent 2 different model simulations. As back ground info the 2 models are trying to simulate the same thing but modelA tries to represent very specific attributes whereas and modelb tries to model a broader range. Table A has n rows which is larger than the m rows in tableB. I'm trying to create a table with the same number of rows (n) as table A where I can see which modelA_IDs relate to modelB_IDs.

TableA:

ModelA_ID  region height weight
1          1       25      7.1            
2          1       70      7.1            
3          1       10      7.2            
4          1       30      7.3
5          1       35      7.4
6          2       30      7.1

TableB:

ModelB_ID  region min_height max_height min_weight max_weight
9001       1        0             50      7.1        7.3    
9002       1        51            100     7.1        7.3
9003       1        0             100     7.4        7.5
9004       2        0             100     7.1        7.5

So in the example above I should end with something along the lines of

ModelA_ID  ModelB_ID    
1        9001            
2        9002            
3        9001            
4        9001      
5        9003     
6        9004

Region is not unique in either table. If it were I think I would join on that, something along the lines of

SELECT  TableA.ModelA_ID TableB.ModelB_ID 
FROM TableA
inner JOIN TableA
ON TableA.region =TableB.region
where 
TableA.height >= TableB.min_height
and TableA.height <= TableB.max_height
and TableA.weight >= TableB.min_weight
and TableA.weight <= TableB.max_weight

However region is not a unique key so I can't do that!

New to SQL as of a couple of days ago but come from a cshell background but new job has sql only policy :-(

Any ideas? It is not something that has to be repeated often so efficiency is not key.

Thanks

Upvotes: 2

Views: 14067

Answers (1)

Vikdor
Vikdor

Reputation: 24124

However region is not a unique key so I can't do that!

It is not mandatory that the JOIN columns must be primary keys in their respective tables.

SELECT 
    TableA.ModelA_ID,
    TableB.ModelB_ID 
FROM 
    TableA
    JOIN TableB
    ON TableA.region = TableB.region
WHERE 
    TableA.height >= TableB.min_height
AND TableA.height <= TableB.max_height
AND TableA.weight >= TableB.min_weight
AND TableA.weight <= TableB.max_weight

Results of the above query are:

ModelA_ID   ModelB_ID
----------- -----------
1           9001
3           9001
4           9001
2           9002
5           9003
6           9004

(6 row(s) affected)

Upvotes: 1

Related Questions