Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the MIN() value of a SUBSTRING()

Tags:

mysql

max

min

I'm having the following problem. Imagine my mySQL table looks like this:

id   range
1    210-400
2    300-310
3    100-350

I want to find

  1. the MIN value of the first part (before the "-") in the range field
  2. the MAX value of the second part (after the "-") in the range field

Now i tried to select the needed parts of that field with SUBSTRING and then get the MIN or MAX value like this:

SELECT
  SUBSTRING_INDEX(`range`,'-',1) as `left_value`,
  SUBSTRING_INDEX(`range`,'-',-1) as `right_value`,
  MIN(`left_value`),
  MAX(`right_value`)
FROM `table`

But i just get "#1054 - Unknown column 'left_value' in 'field list'"

So my question - is this even possible, and how?

like image 568
Lixus Avatar asked Jan 31 '26 22:01

Lixus


1 Answers

You're missing a comma after your 3rd line (after as 'right_value').

However, this probably still won't completely solve your problem. +1 for Devart's answer. To expand, you're probably looking for something closer to this:

SELECT
  MIN(SUBSTRING_INDEX(`range`, '-', 1)),
  MAX(SUBSTRING_INDEX(`range`, '-', -1))
FROM `table`
like image 74
ziesemer Avatar answered Feb 02 '26 13:02

ziesemer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!