gpt4 book ai didi

sql - 根据来自不同表的记录数更新字段

转载 作者:行者123 更新时间:2023-12-04 20:17:27 24 4
gpt4 key购买 nike

我需要在另一个表中给定角色的计数大于 1 的表中将值设置为 1。

表 cursillo.members 有字段 memid 和 hsd。表 cursillo.teams 有字段 memid(两者之间的链接),一个字段称为 movement,另一个字段称为 role。

我想要完成的是类似这样的事情:

update cursillo.members_eligible p, cursillo.teams pp
set p.hsd=1
where p.memid = pp.memid AND (pp.role = 'HSD' OR pp.role = 'SD')
and pp.movement = 'Cursillo' AND count(pp.role) > 1;

或者这个:

update members_eligibile
set hsd=1
from teams
where teams.memid=members_eligible.memid
and (teams.role = 'HSD' OR teams.role = 'SD')
and teams.movement = 'Cursillo'
and count(teams.role) > 1;

换句话说,如果给定的 memid 在 cursillo.teams 表中有多个记录,其中角色的值等于 HSD 或 SD,则将 cursillo.members_eligible.hsd 设置为 1。

我不知道如何处理 count() 部分。

谢谢,迈克·里德

最佳答案

可能重复的问题:

MySQL - Using COUNT(*) in the WHERE clause

尝试使用'having'关键字

这是链接答案中的相关部分(在本例中为 select 语句):

select gid
from `gd`
group by gid
having count(*) > 10
order by lastupdated desc

不过看起来“having”只能用在选择语句中: http://www.mysqltutorial.org/mysql-having.aspx

因此您可能需要让更新的 where 子句包含一个选择语句:

update members_eligibile
set hsd=1
from teams
where teams.memid=members_eligible.memid
and (teams.role = 'HSD' OR teams.role = 'SD')
and teams.movement = 'Cursillo'
and members_eligible.memid IN
(SELECT members_eligible.memid from members_eligible where teams.memid=members_eligible.memid having count(teams.role) > 1);

你将不得不调整select语句,我没有测试过

关于sql - 根据来自不同表的记录数更新字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13336282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com