MySQL查询基于另一个表的ID替换名称

时间:2018-06-21 13:33:48

标签: mysql sql

我有两个表client和well_names

表客户端

id,name
1   ABC
2   TEST
3   XYZ

表井名称

id,operator
1   ABC
2   ABC
3   ABC
4   TEST
5   TEST
6   XYZ
7   XYZ

我想从客户表中选择ID,并在well_names表中的运算符列上进行更新。

预期产量

表井名

id,operator
1   1
2   1
3   1
4   2
5   2
6   3
7   3

4 个答案:

答案 0 :(得分:1)

此查询将起作用:

SELECT a.id, b.id 
FROM clients as a LEFT JOIN well_names as b ON a.name = b.operator

答案 1 :(得分:0)

select w.id as id, 
       c.id as operator
from join tbl_well w 
inner tbl_client c
on c.operator = w.operator

答案 2 :(得分:0)

您可以将subquery与update语句一起使用:

update well_names w
      set operator = (select c.id from Clients c where c.name = w.operator);

答案 3 :(得分:0)

UPDATE well_names WN
INNER JOIN Clients C ON WN.operator = C.operator 
set WN.operator = C.id