开发者

Join 4 tables in MySQL with max row from one table

I have four tables in a MySQL database and I am trying to create a query that joins all four pulling the most recent data from the logs table:

  • ratings (id, rating, deviceId, listingId)
  • data (listingId, name, location)
  • devices (deviceId, model)
  • logs (dateAdded, deviceId, appVersion)

I would like to display: rating, name, location, model, appVersion

The application version change over time so it is kept separate from the devices table.

The following query gets me half way there. The problem is the appVersion is not the most recent.

SELECT ratings.id,ratings.listingId,ratings.rating,data.name,devices.model,tt.appVersion
FROM ratings
JOIN data on ratings.listingId = data.id 
JOIN devices on ratings.deviceIdentifier = dev开发者_如何学JAVAices.deviceIdentifier
JOIN (select max(dateAdded), appVersion, deviceIdentifier from logs) tt
ORDER BY dateAdded DESC;

If I try either of the following statements, the query times out.

SELECT ratings.id,ratings.listingId,ratings.rating,data.name,devices.model,tt.appVersion
FROM ratings
JOIN data on ratings.listingId = data.id 
JOIN devices on ratings.deviceIdentifier = devices.deviceIdentifier
JOIN (select max(dateAdded), appVersion, deviceIdentifier from logs where dateAdded in     
 (select max(dateAdded) from logs group by deviceIdentifier) ) tt
ORDER BY dateAdded DESC;

or

SELECT ratings.id,ratings.listingId,ratings.rating,data.name,devices.model,logs.appVersion
FROM ratings
JOIN data on ratings.listingId = data.id 
JOIN devices on ratings.deviceIdentifier = devices.deviceIdentifier
JOIN (select t.deviceIdentifier, t.appVersion 
    from logs t
    inner join (select deviceIdentifier, max(dateAdded) as dateAdded from logs  
            group by deviceIdentifier) x 
            on t.deviceIdentifier = x.deviceIdentifier and t.dateAdded = x.dateAdded) tt
ORDER BY dateAdded DESC;


EDITED: Corrected small bug. I've tested this and it works.

set @deviceId := 0;
select *
from (select r.id, r.listingId, r.rating, data.name, d.model, d.deviceId, l.appVersion
    FROM ratings r
    JOIN data on r.listingId = data.listingId 
    JOIN devices d on r.deviceId = d.d  eviceId
    JOIN logs l on l.deviceId = d.deviceId
    ORDER BY d.deviceId, dateAdded DESC) x
where @deviceId != deviceId
and (@deviceId := deviceId) is not null;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜