我正在计算玩家等级的MIN
,MAX
和AVG
:
SELECT
MIN(`p`.`level`) AS 'min',
MAX(`p`.`level`) AS 'max',
AVG(`p`.`level`) AS 'avg'
FROM `dfh`.`players` `p`
如何获取引用p.name
和MIN
的{{1}}字段值?
的Fe。我在MAX
表中得到了这个值:
p
查询将撤消以下内容:
Lp. | Name | Level
1 | Test | 12
2 | Tesx | 15
3 | Anot | 150
但我希望它还撤销与MIN: 12
MAX: 150
和Name
值相对应的MIN
:
MAX
我该怎么做?
答案 0 :(得分:2)
尝试此查询 -
SELECT 'MIN' property, GROUP_CONCAT(p1.name) name, p1.level FROM players p1
JOIN (SELECT MIN(level) level FROM players) p2
ON p1.level = p2.level
UNION
SELECT 'MAX' property, GROUP_CONCAT(p1.name) name, p1.level FROM players p1
JOIN (SELECT MAX(level) level FROM players) p2
ON p1.level = p2.level
使用最高'经验'值和任何'id'进行查询 -
SELECT * FROM
(SELECT 'MIN' property, p1.id, p1.level, p1.name FROM players p1
JOIN (
SELECT
level, MAX(experience) experience
FROM
players,
(SELECT @level:=MIN(level) FROM players) t
WHERE level = @level
) p2
ON p1.experience = p2.experience AND p1.level = p2.level
ORDER BY id LIMIT 1) t_min
UNION
SELECT * FROM
(SELECT 'MAX' property, p1.id, p1.level, p1.name FROM players p1
JOIN (
SELECT
level, MAX(experience) experience
FROM
players,
(SELECT @level:=MAX(level) FROM players) t
WHERE level = @level
) p2
ON p1.experience = p2.experience AND p1.level = p2.level
ORDER BY id LIMIT 1) t_max
将此数据集用作子查询以与另一个表连接 -
SELECT * FROM
(
SELECT * FROM
(SELECT 'MIN' property, p1.id, p1.level, p1.name FROM players p1
JOIN (
SELECT
level, MAX(experience) experience
FROM
players,
(SELECT @level:=MIN(level) FROM players) t
WHERE level = @level
) p2
ON p1.experience = p2.experience AND p1.level = p2.level
ORDER BY id LIMIT 1) t_min
UNION
SELECT * FROM
(SELECT 'MAX' property, p1.id, p1.level, p1.name FROM players p1
JOIN (
SELECT
level, MAX(experience) experience
FROM
players,
(SELECT @level:=MAX(level) FROM players) t
WHERE level = @level
) p2
ON p1.experience = p2.experience AND p1.level = p2.level
ORDER BY id LIMIT 1) t_max
) p
LEFT JOIN guild_member gm
ON gm.id = p.id
答案 1 :(得分:1)
这将有效地返回低/高名称 :
select 'MIN', level, name from players order by level limit 1
union all
select 'MAX', level, name from players order by level desc limit 1
注意缺少子查询......