如何使用mysql中的另一个表列填充列

时间:2016-10-20 08:20:46

标签: mysql database join database-design multiple-columns

我有一个名为tbl_employer的表

|  id  | employer |  emp_type  |
|   1  |   aaa    | GOVERNMENT |
|   2  |   bbb    |  PRIVATE   |

我想用这个表tbl_remit加入它,因为tbl_remit的数据是

|RemitNo| id | employer |  emp_cat   |Amt_Remit|  AP_From |   AP_To  |
|  1    |  1 |   aaa    | GOVERNMENT |  20.00  |01/01/2016|01/31/2016|
|  2    |  1 |   aaa    | GOVERNMENT |  10.00  |02/01/2016|02/29/2016|
|  3    |  1 |   aaa    |            |  10.00  |03/01/2016|03/31/2016|
|  4    |  2 |   bbb    |  PRIVATE   |  50.00  |01/01/2016|01/31/2016|
|  5    |  2 |   bbb    |  PRIVATE   |  50.00  |02/01/2016|02/29/2016|
|  6    |  2 |   bbb    |            |  50.00  |03/01/2016|03/31/2016|

我想根据tbl_employer从tbl_remit填充缺少的数据。

|RemitNo| id | employer |  emp_cat   |Amt_Remit|  AP_From |   AP_To  |
|  1    |  1 |   aaa    | GOVERNMENT |  20.00  |01/01/2016|01/31/2016|
|  2    |  1 |   aaa    | GOVERNMENT |  10.00  |02/01/2016|02/29/2016|
|  3    |  1 |   aaa    | GOVERNMENT |  10.00  |03/01/2016|03/31/2016|
|  4    |  2 |   bbb    |  PRIVATE   |  50.00  |01/01/2016|01/31/2016|
|  5    |  2 |   bbb    |  PRIVATE   |  50.00  |02/01/2016|02/29/2016|
|  6    |  2 |   bbb    |  PRIVATE   |  50.00  |03/01/2016|03/31/2016|

我使用了加入声明,但失败了。

SELECT r.RemitNo
     , r.id
     , r.employer
     , (SELECT e.emp_type 
          FROM tbl_employer e
         WHERE e.ID = r.ID) emp_cat
     , amt_remit
     , ap_from
     , ap_to 
  FROM tbl_remit r
  JOIN tbl_employer e 
    ON r.ID = e.ID

2 个答案:

答案 0 :(得分:2)

可能会有所帮助:

UPDATE tbl_remit AS r
JOIN tbl_employer AS e ON e.employer=r.employer    
SET r.emp_cat=e.emp_type

请记住,如果表格中有许多记录,您可能需要在表格中的雇主字段中添加INDEX。我不是100%确定r.id是否等于e.id并且可以用于JOIN但是如果它没问题那么你可以使用这个查询:

UPDATE tbl_remit AS r
JOIN tbl_employer AS e ON e.id=r.id
SET r.emp_cat=e.emp_type

问题中的失败查询应如下所示:

SELECT r.RemitNo
 , r.id
 , r.employer
 , e.emp_type
 , r.amt_remit
 , r.ap_from
 , r.ap_to 
FROM tbl_remit r
JOIN tbl_employer e 
ON r.ID = e.ID

答案 1 :(得分:0)

您需要更新查询

  

更新tbl_remit set emp_cat =(从中选择tbl_employer。emp_type   tbl_employer其中tbl_employer。 id = tbl_remit.id)