簡體   English   中英

SQL:基於列數據聯接到其他表

[英]SQL: Join to different table based on column data

我的情況如下:

表:t_audit

row | colname | oldvalue | newvalue
===================================
1   | locid   | 001      | 002
2   | typeid  | 010      | 011

表格:t_ref_audit

colname | desc        | link_table  | link_key  | link_desc
===========================================================
locid   | Location    | t_ref_loc   | locid     | loc_desc
typeid  | Type        | t_ref_type  | typeid    | type_desc

表格:t_ref_loc

locid | type_desc
==================
001   | LOCATION A
002   | LOCATION B

表格:t_ref_type

typeid | loc_desc
==================
010   | TYPE C
011   | TYPE D

從上面可以看到,第一個表是我的審核日志表,第二個表是參考表。 第三和第四表是參考表。 通過使用下面的簡單SQL,我可以基於t_ref_audit表獲得有關列名的正確描述。

SELECT t_ref_audit.desc, t_audit.oldvalue, t_audit.newvalue
FROM t_audit, t_ref_audit
WHERE t_audit.colname = t_ref_audit.colname

我現在的問題是,t_audit.oldvalue和t_audit.newvalue上的列包含其他參考表(t_ref_loc和t_ref_type)中的參考代碼ID。 我想根據t_ref_audit.link_desc中的列顯示正確的描述,而不僅僅是下面的ID:

coldesc  | oldvalue   | newvalue
==================================
Location | LOCATION A | LOCATION B
Type     | TYPE C     | TYPE D

希望有人能啟發我。 謝謝。

也許是這樣的嗎? (和newvalue的邏輯相同...)

SELECT
  t_ref_audit.desc,
  t_audit.oldvalue,
  t_audit.newvalue,
  case
    when link_table='t_ref_loc' then t_ref_loc.loc_desc
    when link_table='t_ref_type' then t_ref_type.type_desc
    else '???'
  end oldvalue_desc
FROM
  t_audit
  join t_ref_audit ON t_audit.colname = t_ref_audit.colname
  left join t_ref_loc on link_table='t_ref_loc' and oldvalue=locid
  left join t_ref_type on link_table='t_ref_type' and oldvalue=typeid
  • 該邏輯僅適用於靜態映射...
  • 我認為您混合了一些t_ref_loc / t_ref_type表及其標題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM