从具有条件的两个表中选择concat

时间:2014-07-04 18:35:06

标签: mysql join concat

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

## 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那么C1被ALT替换,给出alt_codon = ALT + C2 + C3
  • 如果mutation.pos = reference.pos2那么C2被替换为ALT,给出alt_codon = C1 + ALT + C3
  • 如果mut.pos = reference.pos3那么C1被ALT替换,给出alt_codon = C1 + C2 + ALT

例如在第一行突变,pos = 2786,等于pos3,参考第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;

任何帮助或建议都将非常感谢:)

1 个答案:

答案 0 :(得分:1)

我建议你在变更查询中逐一加入变异表和参考表3次的一种方式这样你就可以使用三个场景案例,在下面的小提琴我已经更新了一些变异表的数据以防万一期望的结果,以匹配ID与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