You don't need a subquery for this. It can be simple and more efficient:
SELECT id_product, date
FROM products
WHERE fk_stat = 1
AND id_order = 77185
ORDER BY id_product DESC
LIMIT 1 ;
Your query is invalid SQL, but MySQL accepts it with the default settings. It will give you a random result. You can change this behavior by adding 'ONLY_FULL_GROUP_BY' to sql_mode.
EDIT: Similar to @MickyT's solution but using a join instead:
SELECT M.*
FROM WEATHER_MEASUREMENT M
JOIN (
SELECT MONTH(CREATED) AS MONTH
, MIN(AMBIENT_TEMPERATURE) AS MIN_TEMP
, MAX(AMBIENT_TEMPERATURE) AS MAX_TEMP
FROM WEATHER_MEASUREMENT M
GROUP BY MONTH(CREATED)
) X
ON MONTH(M.CREATED) = X.MONTH
AND M.AMBIENT_TEMPERATURE IN (X.MIN_TEMP, X.MAX_TEMP);
It is not clear what time that should be used in case of a draw, the query outputs all times where a min or max temp occurred. Assuming that you would like the first occurrence, something like:
SELECT MIN(M.CREATED), M.AMBIENT_TEMPERATURE
FROM WEATHER_MEASUREMENT M
JOIN (
SELECT MONTH(CREATED) AS MONTH
, MIN(AMBIENT_TEMPERATURE) AS MIN_TEMP
, MAX(AMBIENT_TEMPERATURE) AS MAX_TEMP
FROM WEATHER_MEASUREMENT M
GROUP BY MONTH(CREATED)
) X
ON MONTH(M.CREATED) = X.MONTH
AND M.AMBIENT_TEMPERATURE IN (X.MIN_TEMP, X.MAX_TEMP);
GROUP BY M.AMBIENT_TEMPERATURE
can be used.
I left out the predicate for the current month, but that is easily added. Since MySQL does not support LATERAL
join, it is probably better to add that predicate to the derived table as well. I.e.
SELECT MIN(M.CREATED), M.AMBIENT_TEMPERATURE
FROM WEATHER_MEASUREMENT M
JOIN (
SELECT MONTH(CREATED) AS MONTH
, MIN(AMBIENT_TEMPERATURE) AS MIN_TEMP
, MAX(AMBIENT_TEMPERATURE) AS MAX_TEMP
FROM WEATHER_MEASUREMENT M
WHERE (MONTH(DATE(CREATED)) = Month(NOW()))
GROUP BY MONTH(CREATED)
) X
ON MONTH(M.CREATED) = X.MONTH
AND M.AMBIENT_TEMPERATURE IN (X.MIN_TEMP, X.MAX_TEMP);
WHERE (MONTH(DATE(CREATED)) = Month(NOW()))
GROUP BY M.AMBIENT_TEMPERATURE
As @RolandoMySQLDBA points out the WHERE clause can be rewritten in a index friendlier way.
Best Answer
This Version is for MySQL, but it should work on any rdms The subselect get the Max date from the table for every track_id and uses that ti get the wanted row.
But this would select all rows for that track_id, that have that max date.
If you only want you, you need row_number and an Order
db<>fiddle here
And here the same for Postgres
db<>fiddle here
andd a Version of it for SQL Server
db<>fiddle here