如果我有:
2 baskets of oranges with 7 and 10 each
3 baskets of peaches with 12 and 15 each
然后我要设置:
for every orange basket value of maxfruit to 10 and
for every peach basket value of maxfruit to 15
我尝试了
update baskets set maxfruit = (select max(fruitCount) from baskets b where b.fruit = fruit)
,但它只是将所有内容设置为15 ...
在sql中,当您以其名称引用列时,最终使用的表实例是最内在的,除非您使用表前缀。
因此,fruit
指的是最内向的实例b
。这意味着b.fruit
和fruit
始终是相同的值。
要引用外表实例,您必须使用外表的名称:
update baskets
set maxfruit = (select max(fruitCount)
from baskets b
where b.fruit = baskets.fruit);
^^^^^^^^
(而不是b.fruit
,您可以仅编写fruit
,但这还不清楚。)
您的更新只是从整个桌子上拉出最大
UPDATE b
SET b.maxfruit = b2.fruitCount
FROM baskets b
INNER JOIN (SELECT fruit, MAX(fruitCount) AS fruitCount
FROM baskets
GROUP BY fruit) b2 ON b.fruit = b2.fruit