dsyk33753 2012-07-09 09:20
浏览 174
已采纳

从字段中获取最大值和最小值

I have two tables:

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

and i would like show:

id | title | min | max 
1  | aaa   |  1  | 6
2  | bbb   |  1  | 4
3  | ccc   |  1  | 4

Is this possible with SQL? How? :)

  • 写回答

4条回答 默认 最新

  • duan39779 2012-07-09 09:25
    关注

    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
    

    you can remove MIN and MAX (and Group by) if Second can't have many rows with same first_id.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?