UPDATE addr_range
SET rd_id = (
    SELECT rd_id
    FROM rd_rd_el
    JOIN rd USING (rd_id)
    WHERE rd_rd_el.rd_el_id = addr_range.rd_el_id
    ORDER BY CASE
        WHEN (rd_type = 1) THEN 0 /*town street*/
        WHEN (rd_type = 3) THEN 1 /*road construction*/
        WHEN (rd_type = 6) THEN 2 /*road km*/
        WHEN (rd_type = 7) THEN 3 /*named exit*/
        WHEN (rd_type = 5) THEN 4 /*country road*/
        WHEN (rd_type = 4) THEN 5 /*city route*/
        WHEN (rd_type = 2) THEN 6 /*route*/
    END
    LIMIT 1
);

/*Drop addr_ranges without rd*/
DELETE FROM addr_range
WHERE rd_id IS NULL;

