MySQL: MIN () and MAX () vs. String Value

I have a SQL SELECT statement joining 2 tables.
The main table contains various product information and is connected to a second size table.
The second table contains a list of non-numeric sizes stored as a string, and is simply structured as follows:

SizeID = primary key
SizeName = String size value (i.e. Small, Medium, Large)
SizeOrder = An integer to sort the size order (i.e. SizeOrder of 5 will mean that the size was larger than SizeOrder of 2)

I need a SELECT statement to return the MIN () and MAX () sizes from the size table.
However, since the actual size is saved as a string, I need to run the MIN () and MAX () functions in the SizeOrder column, but return the value of the SizeName column.

My current attempt is as follows:

SELECT ProductReference, MIN(SizeOrder) AS MinSizeID, MAX(SizeOrder) AS MaxSizeID, 
(SELECT SizeName FROM Size WHERE SizeOrder = MinSizeID) AS MinSizeText, 
(SELECT SizeName FROM Size WHERE SizeOrder = MaxSizeID) AS MaxSizeText
FROM (Product INNER JOIN Size ON Products.SizeFK = StoneSize.SizeID) 
WHERE ID = 132
GROUP BY ProductReference;

This returns an error "Link" MinSizeID "is not supported (link to group function)"

+3
source share
2 answers

MySQL complains about using column alias in subqueries, try

SELECT ProductReference, MIN(SizeOrder) AS MinSizeID, MAX(SizeOrder) AS MaxSizeID, 
(SELECT SizeName FROM Size WHERE SizeOrder = MIN(Products.SizeOrder)) AS MinSizeText, 
(SELECT SizeName FROM Size WHERE SizeOrder = MAX(Products.SizeOrder)) AS MaxSizeText
FROM (Products INNER JOIN Size ON Products.SizeFK = StoneSize.SizeID) 
WHERE ID = 132
GROUP BY ProductReference;

although I'm not sure if this will complain about the choice of columns not in the group.

+3
source

, SizeOrder , SizeName.

+1

Source: https://habr.com/ru/post/1715404/


All Articles