I have a problem in my sql expression, I want to put different columns in a main select,these different columns has the same where clause.
Here is my sql example:
SELECT t.*,
(SELECT monitor_value
FROM sub_message s
WHERE s.project_name=t.project_name
ORDER BY monitor_time ASC
LIMIT 1) AS project_start_val,
(SELECT monitor_time
FROM sub_message s
WHERE s.project_name=t.project_name
ORDER BY monitor_time ASC
LIMIT 1) AS project_start_time
FROM sub_message t
Your query shows all sub messages with their oldest monitor time and value. The straight-forward approach to this is using window functions (i.e. aggregate functions with an
OVERclause). These are available as of MySQL 8.The simplest way with
FIRST_VALUE:You can also get the first row per project in the from clause:
Before MySQL 8, window functions where not available. There you had to select from the table again. E.g.: