根据列值匹配来插入值

时间:2013-03-12 17:58:49

标签: mysql sql database select case

MySQL初学者在这里。我有两个表(如下所示),其中一个(freqs)我想根据数据在参考列(下面的type_freq)上匹配的列插入值。例如,'rs9'(来自freqs)的类型为'GG',这个'GG'值与type_freq表中的'type2'匹配,我想插入相应的频率(在这种情况下为'。')到'rs9'的频率值。

我尝试使用案例陈述无济于事。我是否正确地认为这最好用几个案例陈述来解决?还有更好的方法吗?我非常感谢任何反馈。谢谢!


表:


TABLE freqs

rsid       type      freq
rs9         GG
rs8         CC
rs1         CC  

TABLE type_freq

 rid       type1    type1_frequency    type2   type2_frequency   type3     type3_frequency
 rs9       AA        .7                GG        .2             GC         .1
 rs8       CC        .5                TT        .3             AT         .2
 rs1       AA        .9                CC        .1             .          .

我的代码:

 UPDATE freqs SET req = 
     (
(SELECT type1_Frequency CASE 
    WHEN type.freqs = type1.type_frequencies
            FROM type_frequencies
    END CASE)
(SELECT type2_Frequency CASE
    WHEN type.freqs = type2.type_frequncies
            FROM type_frequencies
    END CASE)
(SELECT type3_Frequency CASE
    WHEN type.freqs = type3.type_frequencies
            FROM type_frequencies
    END CASE)
    )

1 个答案:

答案 0 :(得分:1)

首先,让我们设计一个查询,创建type_freq表的规范化版本:

SELECT rid, type1 AS type, type1_frequency AS frequency
FROM type_freq
UNION ALL
SELECT rid, type2 AS type, type2_frequency AS frequency
FROM type_freq
UNION ALL
SELECT rid, type3 AS type, type3_frequency AS frequency
FROM type_freq

现在让我们用这个来更新你的表:

UPDATE freqs
SET freq =
(
    SELECT frequency
    FROM
    (
        SELECT rid, type1 AS type, type1_frequency AS frequency
        FROM type_freq
        UNION ALL
        SELECT rid, type2 AS type, type2_frequency AS frequency
        FROM type_freq
        UNION ALL
        SELECT rid, type3 AS type, type3_frequency AS frequency
        FROM type_freq
    ) x
    WHERE x.type = freqs.type AND x.rid = freqs.rsid
)

请注意,如果您可以控制数据库架构,我建议您永久规范化type_freq表。