2011-07-11 56 views
1

我在MySQL數據庫中的四個表,我試圖創建一個連接所有四個從日誌表拉動的最新數據查詢:加入4桌在MySQL中,最大行從一個表

  • 評級(ID,等級,設備ID,listingId)
  • 數據(listingId,名稱,位置)
  • 設備(設備ID,型號)
  • 日誌(dateAdded,DEVICEID,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

編輯:修正小bug。我已經測試過這個,它工作。

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

謝謝......除了我只看到獨特的deviceIds,這個工程很棒。 – sho

+0

我想我有。如果我拿出「where」語句並將其替換爲「group by id」,我會得到期望的結果。 – sho