SQL - 使用另一个表中的数据更新一个表

时间:2017-03-11 03:21:27

标签: mysql sql

我有一种情况,我不知道该怎么做。它是基于来自不同表的数据更新一个表的某个字段。我已经做到了,但有一个问题。这很难解释,但让我给你看一下下表的例子:

tbl_attendance:

| Stud_ID | Stud_Name     |
| 0       | Doe John      |
| 0       | Marquiz, Jane |
| 0       | Mason, Sheena |


tbl_classlist

| Stud_ID | Stud_Name          |
| 0001    | Doe, John          |
| 0002    | Marquez, Jane      |
| 0003    | Mason, Sheyna Kaye |

情况是,在获取以前从csv文件中记录的所有记录之后,2000 +附近发生了太多的文书错误。

如何使用来自tbl_classlist的Stud_ID更新tbl_attendance Stud_ID字段?

到目前为止,我的代码是:

 UPDATE tbl_attendance A 
 INNER JOIN tbl_classlist B on A.Stud_Name=B.Stud_Name
 SET A.Stud_ID = B.Stud_ID;

但这肯定不会奏效。

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE html>
<html>
<head>
    <title>Testing</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.23.1/babel.min.js"></script>
    
</head>
<body>

</body>

<div id="website"></div>
<script type="text/babel" >
    var Website = React.createClass({
  render: function() {
        return(
            <h1>Why won't my h1 tag appear!</h1>
        ); 
    }
});
ReactDOM.render(<Website/>, document.getElementById('website'));
</script>

</html>

几个假设:

  1. 我假设stud_id是tabl_classlist中的varchar2和tabl_attendence中的数字。 2.我认为学生姓名缺少逗号,就像Doe John一样。
  2. 即使这样也可以:

    SELECT * FROM tabl_attendence;
        # stud_id, stud_name
        '0', 'Doe John'
        '0', 'Marquiz, Jane'
        '0', 'Mason, Sheena'
    
    SELECT * FROM tabl_classlist;
    # stud_id, stud_name
    '001', 'Doe, John'
    '002', 'Marquiz, Jane'
    '003', 'Mason, Sheena'
    
    update tabl_attendence a set a.stud_id =
    (select replace(c.stud_id, 0, '') from tabl_classlist c
    where replace(c.stud_name, ',', '') = replace(a.stud_name, ',', ''))
    where (select replace(c.stud_id, 0, '') from tabl_classlist c
    where replace(c.stud_name, ',', '') = replace(a.stud_name, ',', ''));
    
    commit;
    
    SELECT * FROM tabl_attendence;
    # stud_id, stud_name
    '1', 'Doe John'
    '2', 'Marquiz, Jane'
    '3', 'Mason, Sheena'