简体   繁体   中英

Choose join table from column value

Here a simplification of my database structure:

+-----------+    +-----------+    +-------------+
|   data    |    |  int_val  |    | float_val   |
+-----------+    +-----------+    +-------------+
| data_id   |    |  val_id   |    |  val_id     |
|  type     |    |  int_val  |    | float_val   |
| value_ref |    +-----------+    +-------------+
+-----------+

data.value_ref is not declared as foreign key, but it is. The idea is to choose which table to join ( float_val or int_val ) using data.type column .

Can I do this with a single query?

Yes, you can do this with outer joins and a CASE WHEN:

select
    case when type = 'int' 
         then int_val.int_val
         else float_val.float_val
    end
from
    data
    left join int_val on data.value_ref=val_id
    left join float_val on data.value_ref=val_id

This assumes that value_ref will exist in either int_val or float_val, but not both.

SELECT 
    data.id,
    COALESCE(CAST(int_val.int_val AS FLOAT), float_val.float_val) AS value
FROM data
LEFT JOIN int_val
       ON int_val.val_id = data.value_ref
      AND data.type = 'int'
LEFT JOIN float_val
       ON float_val.val_id = data.value_ref
      AND data.type = 'float'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM