我有一个这样的表,我需要设置主键id的男性和女性计数: 的 summaryTable:
id femaleCount maleCount
-----------------------------
s1 ? ?
s2 ? ?
... and so on
如下所示,详细信息表格中包含与 summaryTable 的每个ID对应的用户:
id parentId userId
--------------------------
1 s1 u1
2 s1 u2
3 s2 u2
4 s2 u2
...and so on
第三个是这样的用户表: 的用户表:
userId gender
-------------
u1 M
u2 F
u3 F
..and so on
我必须使用男性和女性的数量更新摘要表。因此,对于id = s1,femaleCount应设置为1,maleCOunt = 1 对于id = s2,femaleCOunt应设置为2,maleCount = 0
这可以在MySQL中使用UPDATE查询吗?
我尝试了以下操作,但这会返回用户出现的总和,即如果u1对p1(例如)发生2次,那么它将返回计数为2而不是1:
SELECT
d.parentId,
SUM(gender = 'F') AS 'F#',
sum(gender = 'M') as 'M#'
FROM detailsTable as d
JOIN userTable as c on c.userId = d.userId
GROUP BY d.parentId;
也尝试如下,但它出错了:
select d.parentId,
count(case when c.gender='M' then 1 end) as male_cnt,
count(case when c.gender='F' then 1 end) as female_cnt,
from detailsTable d, userTable c where d.userId=c.userId group by d.parentId, d.userId ;
此外,我的问题不仅仅是选择结束,我需要获取值,然后在摘要表中更新这些值。
答案 0 :(得分:1)
我可能在MySql的语法上生锈,但我相信这可以满足您的需求。 CASE / SUM实际上是获取计数的枢轴,然后您可以正常更新表。
UPDATE summaryTable AS st
INNER JOIN ( SELECT parentId
,SUM(CASE WHEN gender = 'f' THEN 1
ELSE 0
END) femaleCount
,SUM(CASE WHEN gender = 'm' THEN 1
ELSE 0
END) maleCount
FROM userTable d
INNER JOIN (SELECT DISTINCT parentId, userId FROM detail) ut ON d.userId = ut.userId
GROUP BY parentId
) AS c ON c.parentId = st.parentId
SET femaleCount = c.femaleCount
,maleCount = c.maleCount