vendredi 17 juin 2016

How can I join selectively

Assume I have a table of vehicles:

v            color      col3       col4    col5   .....
car          red
train        gray
plane        white
car          blue
bike         black
(1000 more)

And a table with classifications:

prio     v        color         class
1        car      red           C1
2        car      %             F3
3        plane    %             W1
4        bike     blue          B4
5        bike     white         B8
6        bike     %             O9

The classifications table is small, less then 100. Only a lookup table. if necessary we can add an id column to the vehicles.

Now I want to add the classification to the table of vehicles. The number of rows in vehicles must not change. The result should be:

v            color   class
car          red     C1
train        gray
plane        white   W1
car          blue    F3
bike         black   O9
(1000 more)

Now if I do

SELECT vehicles v
LEFT JOIN classifications c ON v.v LIKE c.v AND v.color LIKE c.color

I get duplicate entries because the classification match is not unique. For example a white bike matches rule 5 and 6, in this case rule 5 must be taken because it has the lower prio.

How can I avoid the duplicates?

Aucun commentaire:

Enregistrer un commentaire