mysql update select语句包含多个表和左外连接

时间:2014-03-04 20:45:00

标签: mysql left-join multiple-columns

我有两个表,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

2 个答案:

答案 0 :(得分:0)

您的查询未指定要更新的所有者,并且它有点扭曲逻辑。 更新,让我知道结果。

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;

答案 1 :(得分:0)

试试这个: -

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