首页 > 解决方案 > 在 mysql 查询中组合结果

问题描述

我有一个 mysql-table (我们称之为table),我在其中存储在游戏中得分的分数。

| ID | SCORE |
|----|-------|
|1   |10     |
|2   |8      |
|3   |15     |
|4   |9      |



我想知道是否有一种简洁的方法可以让一行包含最后一个分数(具有
最高 ID 的那个)和最高分?


目前我正在做

SELECT
    score AS last_score,
    (SELECT MAX(score) FROM table) AS best_score
FROM table
ORDER BY id DESC
LIMIT 1

这正是我想要的:

|last_score|best_score|
|----------|----------|
|9         |15        |

但是在性能方面,我想知道最好不要有两个select:s


我宁愿做一些事情

SELECT
    score AS last_score,
    MAX(score) AS best_score
FROM table
ORDER BY id DESC
LIMIT 1

这给了我最好的分数,但不是最新的。


有什么建议么?

标签: mysql

解决方案


select (SELECT score from purchase ORDER BY id desc LIMIT 1) as last_score, (SELECT MAX(score) as max_score from purchase) as max_score


推荐阅读