php sql查询选择一个字段值最大的行数据

时间:2018-04-15 09:41:38

标签: mysql sql

如何在值最大或最小的表格的行中选择并显示该字段的值?

例如,假设我有balance的以下表格结构。

+------+-------+--------+
| id   | bal   | userid |
+------+-------+--------+
| 1    | 4.00  | 1      |
| 2    | 8.35  | 2      |
| 3    | 15.67 | 3      |
| 4    | 10.00 | 4      |
+------+-------+--------+

在这里,我想向用户展示最大平衡和最小平衡。我的查询应该选择什么才能显示出来?在这种情况下,用户3具有最大余额,用户1具有最小值。我想选择它们,然后使用membersmem_id表格左右加入,以提取用户名mem_uname并显示其余额。

2 个答案:

答案 0 :(得分:0)

一个选项是以下联合查询:

(SELECT *, 'max user' AS type FROM balance ORDER BY bal DESC LIMIT 1)
UNION ALL
(SELECT *, 'min user' FROM balance ORDER BY bal LIMIT 1)

这假设您不需要担心最大/最小平衡的关系。如果这是一个问题,那么我们将不得不做更多的工作:

SELECT *, 'max users' AS type
FROM balance
WHERE bal = (SELECT MAX(bal) FROM balance)
UNION ALL
SELECT *, 'min users'
FROM balance
WHERE bal = (SELECT MIN(bal) FROM balance)
ORDER BY type;

答案 1 :(得分:0)

尝试以下查询

(select * from balance where bal=(select max(bal) from balance))
union all
(select * from balance where bal=(select min(bal) from balance));

OUT PUT

+------+-------+--------+
| id   | bal   | userid |
+------+-------+--------+
|    3 | 15.67 |      3 |
|    1 |     4 |      1 |
+------+-------+--------+