我有两张桌子,TableA
&TableB
所有表格数据均可在此处获取:db<>fiddle
我想要用特定tableA
的数据更新。tableB
A_id
因此,我编写了更新的查询A_id=2
如下:
UPDATE TableA
SET
total_count = (SELECT COUNT(A_id) AS total_count
FROM TableB WHERE A_id = 2),
pass_count = (SELECT COUNT(CASE WHEN(isPassed = 'Y') THEN 1 END) as pass_count
FROM TableB WHERE A_id = 2),
fail_count = (SELECT COUNT(CASE WHEN(isPassed = 'N') THEN 1 END) as fail_count
FROM TableB WHERE A_id = 2)
WHERE A_id = 2;
并检查TableA
其更新数据是否正确。
但是,上述查询对于每个列更新都有 3 个不同的子查询。
因此,我想编写更新后的查询,如下所示:
WITH T0 AS (
SELECT A_id,
COUNT(A_id) AS TOTAL_SCENARIOS_COUNT,
COUNT(CASE WHEN(isPassed = 'Y') THEN 1 END) as PASS_SCENARIOS_COUNT,
COUNT(CASE WHEN(isPassed = 'N') THEN 1 END) as FAIL_SCENARIOS_COUNT
from RT_TEST_RUN_SCENARIO
GROUP BY A_id
HAVING A_id = 4779
)
UPDATE tableA
SET
tableA.total_count = t0.total_count,
tableA.pass_count = t0.pass_count,
tableA.fail_count = t0.fail_count
FROM tableA INNER JOIN T0
ON tableA.A_id = T0.A_id
还有其他方法可以更新吗TableA
?
注意:所有表格数据/查询都可以在这里找到:db<>fiddle
您当前的更新存在多个问题,最大的问题是您似乎使用了 SQL Server 的更新连接语法。MySQL 更新连接语法首先执行连接,然后执行集合。此外,您使用的别名不一致,并且存在问题。以下版本按预期运行。
演示
顺便说一句,鉴于中的数据
TableA
来自源TableB
,您可能需要考虑仅基于T0
cte 创建一个视图,然后在需要以这种方式查看数据时调用它。替代答案是:
https://dbfiddle.uk/2y9O-TkK?highlight=2