SELECT语句中的MAX

时间:2013-06-08 23:47:00

标签: mysql database select insert

username   level
me          1
you         1
me          2
me          3
you         1

我想获得每个用户名的最高价值。所以它应该给我3个'我',1个给'你'。我如何在SELECT语句中执行此操作?

INSERT INTO table1 (username, level)
SELECT username, (MAX(level)
WHERE username=username group by username)
FROM table2

^它应该是那样的,但我无法弄明白。

- EDIT-- 这给了我整个级别和exp列的相同值,而它们肯定不完全相同:

INSERT INTO oitc_test (username, xpboost_expiration, level, exp, kills, games) 
SELECT oitc.username, oitc.xpboost_expiration, MAX(oitc.level), MAX(oitc.exp), oitc_sum.kills, oitc_sum.games 
FROM oitc, oitc_sum 
GROUP by username;

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您正在尝试复杂的查询;一个简单的任务。

INSERT INTO table1 (username, level) 
SELECT username, MAX(level)
FROM table2
GROUP BY username

对于第二个问题,您需要使用JOIN子句。

INSERT INTO oitc_test (username, xpboost_expiration, level, exp, kills, games) 
SELECT o.username, o.xpboost_expiration, MAX(o.level), MAX(o.exp), os.kills, os.games 
FROM oitc o
INNER JOIN oitc_sum os
    ON o.username = os.username
GROUP BY o.username;

我认为username是表格中的共同键 oitc oitc_sum