Search code examples
mysqlmathcubes

Calculating the largest side of a 3d object - MySQL function to select second greatest value


I have three fields for width, height and depth. Let's say I have these values

width = 5
height = 0.1
depth = 3

I would like to filter out greatest two values from these values and do maths for two dimensions to find out the largest side.

It should be a * b

a = GREATEST(width, height, depth) /* greatest value selected */
b = GREATEST(width, height, depth) /* <-- select the second greatest value here */

The reason why I can't ignore width here is that I don't know which one of the width, height, depth has the max value and selected as the value of a

EDIT: Didn't mention that these fields may contain NULL values

EDIT: The table contains dimensions for 2D objects to. In some cases depth may not exist. It can be NULL


Solution

  • If the types are float, you may get rounding errors with this:

    a = GREATEST(width, height, depth)   /* greatest value selected */
    c = LEAST(width, height, depth)
    b = width + height + depth - a - c   /* middle value */
    

    Another route:

    b = ( SELECT width AS side
          FROM tableX
          WHERE pk = externalTable.pk
        UNION ALL
          SELECT height
          FROM tableX
          WHERE pk = externalTable.pk
        UNION ALL
          SELECT depth
          FROM tableX
          WHERE pk = externalTable.pk
        ORDER BY side DESC
          LIMIT 1 OFFSET 1
        )