作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有一个包含分组行的表格,这些行在一列中共享一个值,但它们在另一列中很少不同。
我需要能够在下面的 portfolio_id
没有差异时更新它们,或者最好,至少在 90% 的情况下没有差异(我意识到这可能很棘手).
表结构
mytable1
table1id | parentgroup | portfolio_id
1 | 100 | 3
2 | 100 | 3
3 | 100 | 3
4 | 203 | 4
5 | 203 | 5
6 | 500 | 7
mytable2
以及预期结果
count | parentgroup | portfolio_id
3 | 100 | (trying to fill with a 3)
2 | 203 | (shouldn't fill since half the dots are split within 2 portfolios)
1 | 500 | (trying to fill with a 7)
我的查询看起来像
update mytable2 a
set portfolio_id = (select portfolio_id from mytable1 b
where a.parentgroup = b.parentgroup)
where parentgroup is not null
但显然我得到了错误
SQL Error [21000]: ERROR: more than one row returned by a subquery used as an expression
如何规避这个?
最佳答案
这是一个使用带有更新连接的 CTE 的选项:
WITH cte AS (
SELECT parentgroup, MAX(portfolio_id) AS portfolio_id
FROM mytable1
GROUP BY parentgroup
HAVING MIN(portfolio_id) = MAX(portfolio_id)
)
UPDATE mytable2 a
SET portfolio_id = b.portfolio_id
FROM cte AS b
WHERE a.parentgroup = b.parentgroup;
这里的想法是 CTE 为第一个表中的每个 parentgroup
找到 portfolio_id
的奇异值(如果存在奇异值)。然后,我们通过仅针对与 CTE 中的任何内容匹配的 parentgroup
组来更新第二个表。
关于sql - 如何在没有 "ERROR: more than one row returned by a subquery used as an expression"的情况下更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52813936/
我是一名优秀的程序员,十分优秀!