[英]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:我在 MySQL 数据库中有四个表,我正在尝试创建一个查询来连接所有四个从日志表中提取最新数据的查询:
I would like to display: rating, name, location, model, appVersion我想显示:评级、名称、位置、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.
问题是 appVersion 不是最新的。
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) 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.