Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

troubleshooting Question

How to get last record of each group

Avatar of rudy2024
rudy2024 asked on
MySQL Server
4 Comments1 Solution1010 ViewsLast Modified:
Hi Experts,
I am using a MySQL database and I have a couple of tables, one for measurements and another for last measured values. When I insert data into the measurement table I usually do bulk inserts and I need help figuring out the last measured values inserted.

The following example will clarify what I am trying to do.

Table that contains all the measurements:

CREATE TABLE measurement(
sensor_id INT,
meas_type INT,
meas_val FLOAT,
meas_date_time TIMESTAMP

Table that contains the last measurement:

CREATE TABLE last_measurement(
sensor_id INT,
meas_type INT,
meas_val FLOAT,
meas_date_time TIMESTAMP,
PRIMARY KEY ('sensor_id', 'meas_type')

Step 1: Get meas_id from measurement table (first_id)
Step 2: Bulk insert a bunch of measurements
Step 3: Get meas_id from measurement table (last_id)

Then I need to get the records that contain the most recent measurement for the combination of sensor_id, meas_type.

To get the max date I can use:
SELECT sensor_id, meas_type, MAX(meas_date_time) FROM measurement
WHERE meas_id >= first_id AND meas_id <= last_id;

But I don't know how to include meas_val on that query.

I tried:
SELECT sensor_id, meas_type, MAX(meas_date_time), meas_val FROM measurement
WHERE meas_id >= first_id AND meas_id <= last_id;

But the meas_val does not correspond to the max(meas_date_time) it corresponds to the first record.