如何用另一个表中的标签替换值

时间:2018-01-29 09:54:55

标签: sql oracle

我有一些包含有用信息的表,但是用数字编码,一个表包含数字代码和标签之间的映射。以下是示例:

客户:

 id* | name | gender | group
----------------------------
   1 | M.T. |      0 |     1 
   2 | H.F. |      0 |     2 
   3 | Y.Y. |      1 |     1 

档案:

 iid* | id | item
------------------
   1  |  1 |  123
   2  |  2 |  456
   3  |  2 |  789

标签:

 key* |    table | column | value |     label
----------------------------------------------
   1  | Customer | gender |     0 |         M
   2  | Customer | gender |     1 |         F
   3  | Customer |  group |     1 |      Gold
   4  | Customer |  group |     2 |    Sliver
   5  | Customer |  group |     3 |    Bronze
   6  |     Item |   item |   123 | Product A
   7  |     Item |   item |   124 | Product B
   8  |     Item |   item |   456 |  Item 456
   9  |     Item |   item |   789 |    Book Y
  10  |     Item |   item |   790 |    Book Z

我想在Customer和Item上生成查询结果,如下所示。

客户:

 id | name | gender |  group
-----------------------------
  1 | M.T. |      M |   Gold 
  2 | H.F. |      M | Sliver 
  3 | Y.Y. |      F |   Gold 

档案:

 iid | id |      item
----------------------
  1  |  1 | Product A
  2  |  2 |  Item 456
  3  |  2 |    Book Y

以下是我编写的用于生成结果的SQL。

查询客户:

select
  c.id,
  c.name,
  l1.label as gender,
  l2.label as group
from Customer c
left join Label l1 
  on l1.table = 'Customer' and l1.column = 'gender' and c.gender = l1.value
left join Label l2 
  on l2.table = 'Customer' and l2.column = 'group' and c.group = l2.value

查询项目:

select
  i.iid,
  i.id,
  l1.label as item
from Item i
left join Label l1
  on l1.table = 'Item' and l1.column = 'item' and l1.value = i.item

有没有更好的SQL来做这些事情?

如何在Label表中使用 table 中的值,这样我就不需要对表名和列名进行硬编码来映射标签?

如果要通过标签映射许多列,我的SQL需要许多LEFT JOIN子句。这是可以避免的吗?

1 个答案:

答案 0 :(得分:0)

  

如果要通过标签映射许多列,我的SQL需要很多   LEFT JOIN条款。这是可以避免的吗?

此数据模型有点可疑,但如果您必须处理它,则可以使用pivotcase when避免多个左连接:

<强> SQL Fiddle demo

select c.id, c.name, 
       max(case when col = 'gender' then label end) gender,
       max(case when col = 'group'  then label end) grp
  from customer c
  left join label l 
    on l.tbl = 'Customer' and (l.col, l.value) in (('gender', c.gender), ('group', c.grp))
  group by c.id, c.name

尽量避免将列命名为&#34; table&#34;,&#34; column&#34;,&#34; group&#34 ;,它们在Oracle中为reserved words