1
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-- 这给了我整个 level 和 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;

我究竟做错了什么?

4

1 回答 1

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是表oitcoitc_sum

于 2013-06-08T23:49:49.940 回答