1

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

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


表:


表频率

rsid       type      freq
rs9         GG
rs8         CC
rs1         CC  

表类型频率

 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)
    )
4

1 回答 1

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表。

于 2013-03-12T18:02:49.620 回答