SQL-在列值上连接两个表=列名

时间:2017-04-04 06:18:39

标签: mysql sql left-join

加入两张桌子后,我遇到了一个真正的问题。

我有这个主表:

----------------
|ID|Stock|Group|
|--+-----+-----|
|K3|US 11|1    |
|K3|US 23|2    |
|K3|HK 10|2    |
|G5|SG 56|1    |
|D1|PH 12|1    |
|D1|UK 23|2    |
----------------

和这个映射表:

------------------------------------
|ID|Local1|Local2|Foreign1|Foreign2|
|--+------+------+--------+--------|
|K3|10    |20    |25      |30      |
|G5|20    |30    |35      |40      |
|D1|10    |15    |20      |50      |
------------------------------------

如何将Stock和Group值的组合映射到映射表的列?         其中US=Local*others*=Foreign。 例如,第1组中K3的库存 US 11 US 11 表示市场是本地的。如何从映射表中获取Column Local1的值? 然后将结果加入表中,如下所示:

----------------------
|ID|Stock|Group|Ratio|
|--+-----+-----+-----|
|K3|US 11|1    |10   |
|K3|US 23|2    |20   |
|K3|HK 10|2    |30   |
----------------------

我没有尝试任何东西,因为我不知道该怎么做。请帮忙。

3 个答案:

答案 0 :(得分:5)

如果我理解正确,以下内容应该是您所需要的:

Select
    m.ID,
    m.Stock,
    m.[Group],
    Case
        when left(m.stock,2)='US' and m.[Group] =1 then mapping.Local1
        when left(m.stock,2)='US' and m.[Group] =2 then mapping.Local2
        when m.[Group]=1 then mapping.Foreign1
        Else mapping.Foreign2
    End as Ratio
From
    Main m
    Join mapping on main.id = mapping.id

答案 1 :(得分:1)

您使用外键加入表

从{{1}选择mainidmainstockmaingroupcreate_ratio_here } main mapping = mappingid mainid = k3

答案 2 :(得分:1)

您可以使用特定的选择案例来设置您真正需要的地图(但是是专用解决方案)

  select a.id,a.Stock, a.Group,
      case  when  stock ='US 11' and group = 1 then b.Local1
            when  stock ='US 23' and group = 2 then b.Local2
            when  stock ='HK 10' and group = 2 then b.Foreign2
            .....
  from main as a
  inner join mapping as b on a.id=b.id 
相关问题