在MySQL中加入4个表,从一个表中加入最大行

时间:2011-07-11 01:29:37

标签: mysql

我在MySQL数据库中有四个表,我正在尝试创建一个连接所有四个从日志表中提取最新数据的查询:

  • 评级(id,rating,deviceId,listingId)
  • 数据(listingId,名称,位置)
  • 设备(deviceId,型号)
  • logs(dateAdded,deviceId,appVersion)

我想显示: 评级,名称,位置,型号,appVersion

应用程序版本随时间而变化,因此它与设备表保持独立。

以下查询让我走了一半。问题是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;

如果我尝试以下任一语句,查询就会超时。

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;

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;

1 个答案:

答案 0 :(得分:1)

编辑:纠正了小错误。我已经测试了这个并且它可以工作。

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;