Home > Database > Mysql Tutorial > How to Retrieve the Latest Status for Each Service Using SQL Joins?

How to Retrieve the Latest Status for Each Service Using SQL Joins?

Barbara Streisand
Release: 2025-01-04 22:16:44
Original
850 people have browsed it

How to Retrieve the Latest Status for Each Service Using SQL Joins?

Latest Status Data with Inner Join and Limit

This challenge involves retrieving the latest status for each service from two tables: Service and Status. The Service table contains service information, while the Status table holds status updates with timestamped records.

To achieve this, an inner join can be used to combine the tables based on the service_id column. However, the challenge arises when selecting the latest status for each service. The following statement retrieves only the latest status for the last service:

SELECT ser.id, ser.name, a.status, a.timestamp
from Service ser
  inner join (select * from status
              order by Status.timestamp
              DESC limit 1) as a
    on a.service_id = ser.id
Copy after login

To retrieve the latest status for each service, a nested query is required:

SELECT 
  ser.id, 
  ser.name, 
  s.status, 
  s.timestamp 
FROM Service ser 
INNER JOIN status as s ON s.service_id = ser.id
INNER JOIN
(
   SELECT
     service_id, 
     MAX(timestamp) AS MaxDate
   FROM status 
   GROUP BY service_id
) AS a  ON a.service_id = s.service_id 
       AND a.MaxDate = s.timestamp;
Copy after login

The nested query retrieves the maximum timestamp for each service, which represents the latest status for that service. The results are then joined with the main query to display the latest status data for each service.

Using this approach, the desired output is achieved:

id name status timestamp
1 Test1 OK October, 15 2015 09:08:07
2 Test2 OK October, 15 2015 10:15:23

The above is the detailed content of How to Retrieve the Latest Status for Each Service Using SQL Joins?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template