MySQL - 如何使用另一个表中的值更新一个表?

发布于 2024-09-12 13:10:36 字数 548 浏览 3 评论 0原文

我的任务是修复 mysql 数据库中的一些无效数据。在一个表中,有人缺少日期,如果有相应的条目,则应从第二个表中填充该日期。

TablePeople:ID、MissingDate、...
TableEvent: ID, people_id, replacementDate, ...

Update TablePeople 
   set missingdate = (select replacementDate 
                        from TableEvent 
                       where people_id = TablePeople.ID)   
where  missingdate is null  
  and (select count(*) 
         from TableEvent 
        where people_id = TablePeople.ID) > 0

当然不行。 SQL还有其他方法吗?或者我如何处理 mysql 中的单行来完成它?

I have the task to repair some invalid data in a mysql-database. In one table there are people with a missing date, which should be filled from a second table, if there is a corresponding entry.

TablePeople: ID, MissingDate, ...
TableEvent: ID, people_id, replacementDate, ...

Update TablePeople 
   set missingdate = (select replacementDate 
                        from TableEvent 
                       where people_id = TablePeople.ID)   
where  missingdate is null  
  and (select count(*) 
         from TableEvent 
        where people_id = TablePeople.ID) > 0

Certainly doesn't work. Is there any other way with SQL? Or how can I process single rows in mysql to get it done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

送舟行 2024-09-19 13:10:36

我们需要有关哪些内容不起作用的详细信息,但我认为您只需要使用:

UPDATE TablePeople 
   SET missingdate = (SELECT MAX(te.replacementDate)
                        FROM TABLEEVENT te
                       WHERE te.people_id = TablePeople.id)   
 WHERE missingdate IS NULL

Notes

  • MAX 被用于返回最新的替换日期,因为担心从子查询中获取多个值的风险
  • 如果 TABLEEVENT 中没有支持记录,它将返回 null,因此没有任何变化

We need details about what's not working, but I think you only need to use:

UPDATE TablePeople 
   SET missingdate = (SELECT MAX(te.replacementDate)
                        FROM TABLEEVENT te
                       WHERE te.people_id = TablePeople.id)   
 WHERE missingdate IS NULL

Notes

  • MAX is being used to return the latest replacementdate, out of fear of risk that you're getting multiple values from the subquery
  • If there's no supporting record in TABLEEVENT, it will return null so there's no change
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文