【问题标题】:SELECT concat from two tables with condition从有条件的两个表中选择连接
【发布时间】:2014-08-26 02:17:45
【问题描述】:

我有两个表突变和参考如下:

## Mutation
mysql> select * from mutation limit 10;
+------+------+------+------+-----------+
| pos  | ref  | alt  | name | alt_codon |
+------+------+------+------+-----------+
| 6    | C    | T    | ND1  | NULL      |
| 10   | T    | C    | ND1  | NULL      |
| 2799 | A    | G    | ND1  | NULL      |
| 2808 | C    | T    | ND1  | NULL      |
| 2825 | T    | C    | ND1  | NULL      |
| 2847 | A    | G    | ND1  | NULL      |

## Reference
mysql> select * from reference limit 10;
+------+------+------+----------+------+------+------+
| pos1 | pos2 | pos3 | codon    | c1   | c2   | c3   |
+------+------+------+----------+------+------+------+
|    1 |    2 |    3 | TTC      | T    | T    | C    |
|    4 |    5 |    6 | GTC      | G    | T    | C    |

对于表突变中的每一行,如果列 pos 与表引用中的 pos1 或 pos2 或 pos3 匹配,则应按如下方式更新表突变中的列 alt_codon:

  • 如果 mutation.pos = reference.pos1 THEN C1 被 ALT 替换,得到 alt_codon = ALT + C2 + C3
  • 如果 mutation.pos = reference.pos2 THEN C2 被 ALT 替换,得到 alt_codon = C1 + ALT + C3
  • 如果 mutation.pos = reference.pos3 THEN C1 被 ALT 替换,得到 alt_codon = C1 + C2 + ALT

例如在mutation的第一行,pos = 2786,等于pos3,在reference中的第3个,到alt_codon应该是c1 + c2 + alt = GTT

我想我应该使用带别名的 UNION 语句,但我想不出办法,并写了一段不起作用的查询:

UPDATE mutation CROSS JOIN reference ON
(mutation.pos = reference.pos1 OR mutation.pos = reference.po2 OR mutation.pos = reference.pos3)
SET mutation.alt_codon = 
CASE WHEN mutation.pos = reference.pos1 THEN (SELECT CONCAT(mutation.alt, reference.c2, reference.c3))
WHEN mutation.pos = reference.pos2 THEN (SELECT CONCAT(reference.c1, mutation.alt, reference.c3))
WHEN mutation.pos = reference.pos3 THEN (SELECT CONCAT(reference.c1, reference.c2, mutation.alt))
ELSE mutation.alt_codon END;

任何帮助或建议将不胜感激:)

【问题讨论】:

    标签: mysql join concat


    【解决方案1】:

    我建议您在更新查询中分别将突变表与参考表连接 3 次的一种方式,您可以使用三种场景案例,在下面的小提琴中,我已经更新了突变表的一些数据,以防产生将 ids 与 pos1,2 和 3 与参考表匹配的期望结果

    update Mutation m
    join Reference r on(m.`pos` = r.`pos3`)
    set m.`alt_codon` = CONCAT(r.`c1`, r.`c2`,m.`alt`);
    
    update Mutation m
    join Reference r on(m.`pos` = r.`pos2`)
    set m.`alt_codon` = CONCAT(r.`c1`,m.`alt`, r.`c3`);
    
    update Mutation m
    join Reference r on(m.`pos` = r.`pos1`)
    set m.`alt_codon` = CONCAT(m.`alt`, r.`c2`,r.`c3`);
    

    See Demo

    【讨论】:

    • 谢谢,它真的很好用而且很简单,我不敢相信我之前没有考虑过!
    猜你喜欢
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 2013-03-31
    • 2016-08-02
    • 1970-01-01
    • 2017-06-29
    • 2020-05-21
    相关资源
    最近更新 更多