2013-03-12 62 views
1

MySQL初學者在這裏。我有兩個表(如下所示),其中一個(頻率)我想根據數據與參考列(type_freq下面)匹配的列來插入值。例如,'rs9'(來自freqs)的類型爲「GG」,該'GG'值與type_freq表中的'type2'匹配,並且我想將相應的頻率(本例中爲'.2')插入到頻率值爲'rs9'。根據列值匹配的值插入值

我試着玩弄案件陳述無濟於事。我是否認爲這最好通過幾個案例陳述來解決?有沒有更好的方法?我非常感謝任何反饋。謝謝!


表:


表freqs

rsid  type  freq 
rs9   GG 
rs8   CC 
rs1   CC 

表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

首先,讓我們設計了創建您的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表。

+0

工作像一個魅力。非常感謝代碼和永久標準化建議。這是一個好主意,我會把它傳遞給控制它的人。對此,我真的非常感激! – ben 2013-03-12 18:23:04

+0

對於後期回覆抱歉,但任何想法爲什麼查詢可能會返回錯誤:「子查詢返回多個行」? – ben 2013-03-12 18:47:34

+0

@ben對於給定的{type,rsid}對必須有兩個不同的值。 – 2013-03-13 04:41:43