本文介绍了从字段中获取最大值和最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两张桌子:
First:
id | title
1 | aaa
2 | bbb
3 | ccc
Second:
id | first_id | one | two | three | four
1 | 1 | 3 | 1 | 4 | 6
2 | 2 | 4 | 4 | 1 | 2
3 | 3 | 1 | 2 | 3 | 4
我想显示:
id | title | min | max
1 | aaa | 1 | 6
2 | bbb | 1 | 4
3 | ccc | 1 | 4
这可以用 SQL 实现吗?如何?:)
Is this possible with SQL? How? :)
推荐答案
阅读 Tom 的回答,这是最好的做法.
Read Tom's answer, this would be the best to do.
无论如何,我感到很惭愧:
Anyway, and shame on me :
SELECT f.id, f.title
MIN(LEAST(s.one, s.two, s.three, s.four)) as min,
MAX(GREATEST(s.one, s.two, s.three, s.four)) as max
FROM First f
INNER JOIN Second s on f.id = s.first_id
GROUP BY f.id, f.title
如果 Second 不能有许多具有相同 first_id 的行,您可以删除 MIN 和 MAX(以及分组依据).
you can remove MIN and MAX (and Group by) if Second can't have many rows with same first_id.
这篇关于从字段中获取最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!