mysql SQL使用group by子句更新查询

pjngdqdw  于 2023-04-10  发布在  Mysql
关注(0)|答案(9)|浏览(243)
Name         type       Age
-------------------------------
Vijay          1        23
Kumar          2        26
Anand          3        29
Raju           2        23
Babu           1        21
Muthu          3        27
--------------------------------------

编写一个查询,将每个类型中最大年龄的人的姓名更新为“HIGH”。
也请告诉我,为什么下面的查询不工作

update table1 set name='HIGH' having age = max(age) group by type;
kdfy810k

kdfy810k1#

我已经改变了Derek的脚本,它现在对我有效(MySQL):

UPDATE table1 AS t 
INNER JOIN 
(SELECT type,max(age) mage FROM table1 GROUP BY type) t1 
ON t.type = t1.type AND t.age = t1.mage 
SET name='HIGH'
pxyaymoc

pxyaymoc2#

你不能在update语句中直接使用group by。它看起来应该像这样:

update t
set name='HIGH'
from table1 t
inner join (select type,max(age) mage from table1 group by type) t1
on t.type = t1.type and t.age = t1.mage;
bvn4nwqk

bvn4nwqk3#

由于我查找了这个回复,发现它读起来有点混乱,我尝试确认以下查询 * 确实 * 有效,证实了Svetlana的高度赞同的原始帖子:

update archives_forum f
inner join ( select forum_id, 
    min(earliest_post) as earliest, 
    max(earliest_post) as latest 
  from archives_topic 
    group by forum_id 
  ) t 
  on (t.forum_id = f.id)
set f.earliest_post = t.earliest, f.latest_post = t.latest;

现在你知道了我也知道了

pkbketx9

pkbketx94#

可以使用半联接:

SQL> UPDATE table1 t_outer
  2     SET NAME = 'HIGH'
  3   WHERE age >= ALL (SELECT age
  4                       FROM table1 t_inner
  5                      WHERE t_inner.type = t_outer.type);

3 rows updated

SQL> select * from table1;

NAME             TYPE AGE
---------- ---------- ----------
HIGH                1 23
HIGH                2 26
HIGH                3 29
Raju                2 23
Babu                1 21
Muthu               3 27

6 rows selected

您的查询将不起作用,因为您不能直接在按查询分组中比较聚合和列值。此外,您不能更新聚合。

scyqe7ek

scyqe7ek5#

试试这个

update table1 set name='HIGH' having age in(select max(age) from table1 group by type);
dsf9zpds

dsf9zpds6#

你可以使用下面的代码。

Update table1#
inner Join (Select max(age) as age, type from Table1 group by Table1) t ON table.age = t.age#
Set name = 'High'#
mum43rcc

mum43rcc7#

update table1 set Name='HIGH' where Age in(select max(Age) from table1)
hgqdbh6s

hgqdbh6s8#

UPDATE table1 SET name = 'HIGH' WHERE age IN (SELECT MAX(age) FROM table1 GROUP BY name)
bfrts1fy

bfrts1fy9#

不能对Update语句使用GroupBy子句。在此期间必须使用子查询

Update table1
Set name = 'High'
From table1 
Join (Select max(age), type from Table1 group by Table1) t ON table1.age = t.age

相关问题