【问题标题】:mysql update select statement with multiple tables and left outer joinmysql更新带有多个表和左外连接的选择语句
【发布时间】:2025-12-09 21:15:01
【问题描述】:

我有两个表,hires_owner 和 projects,其中hires_owner 是项目中数据的汇总表。我想使用项目数据定期更新hires_owner。表结构如下:

**hires_owner**

id INT(11) AUTO-INCREMENT
owner CHAR(25) UNIQUE
hires_total INT(3)

Sample data:
1, tim, 0
2, jack, 3
3, brian, 1
etc.

**projects**

id INT(11) AUTO-INCREMENT
date DATE() **this is the report date stamp, not date of activity
owner CHAR(25)
accept DATE()

sample data:
1, 2014-02-01, jack, 2014-01-02
2, 2014-02-01, jack, 2014-01-03
3, 2014-02-01, tim, NULL
etc.

这个查询得到了我想要推送到hires_owner 表中的结果:

select owner, count(accept) 
from projects 
where date = (select max(date) from projects) 
group by owner

...但我似乎无法正确获取更新查询。这是一次尝试:

update hires_owner h
set hires_total = p.Hires   
(select owner, count(accept) as Hires
from projects 
where date = (select max(date) from projects) 
group by owner) p
where p.owner = h.owner

【问题讨论】:

    标签: mysql left-join multiple-columns


    【解决方案1】:

    试试这个:-

    update
    hires_owner h
    inner join
    (select owner, count(accept) num_c
    from projects 
    where date = (select max(date) from projects) 
    group by owner) p
    on h.owner = p.owner
    set h.hires_total = num_c
    

    【讨论】:

    • 这很有效 - 感谢您的指导。不使用“内部连接”或将 set 语句放在最后是我的失败。再次感谢。
    【解决方案2】:

    您的查询没有指定要更新的所有者,这有点扭曲逻辑。 更新了,告诉我结果。

    update hires_owner set hires_total = p.m
    from (select max(count(accept)) as m, owner as o
                       from projects 
                       where date = (select max(date) from projects)
                       group by owner) as p
    where hires_owner = p.o;
    

    【讨论】:

    • 收到以下错误:“#1064 - 您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,了解在 'select owner, max(count (accept)) as Hires from projects where date = (select ' at line 3..."
    • 我实际上正在努力。你介意使用两个查询来代替吗? @tim_schaaf
    • 你的意思是两个顺序查询吗?我想我可以吗?
    • @tim_schaaf 很高兴您找到了有效的答案,您介意尝试 update-set-from 子句是否有效吗?
    • 嗨@SCV - 我试了一下遇到了语法错误(#1064 - 你的 SQL 语法有错误;查看与你的 MySQL 服务器版本相对应的手册以获取正确的语法在第 2 行使用 near 'from (select max(count(accept)) as m, owner as o from projec')
    最近更新 更多