2015-04-02 68 views
0

使用this SO answer我創建了以下查詢:如何在連接中轉換此子查詢?

select 
    created, property_id, requesting_user_id, type, response 
from 
    pdr t1 
where 
    t1.created = (
     select max(created) 
     from pdr t2 
     where t2.property_id = t1.property_id and t2.requesting_user_id = t1.requesting_user_id 
    ) 

這個工程就像一個魅力,但我現在想使用連接改造這個(也可作爲建議的SO回答我上面鏈接)來查詢。所以,我想出了這個:

select 
    created, property_id, requesting_user_id, type, response 
from 
    pdr t1 
inner join (
    select max(created) as created, property_id, requesting_user_id 
    from pdr 
    group by property_id, requesting_user_id 
) as t2 on t2.property_id = t1.property_id and t2.requesting_user_id = t1.requesting_user_id and t2.created = t1.created 

不幸的是這將返回一個錯誤說ambiguous column name: created。所以我在把一些創建的東西放在t1.t2.之前搞砸了,但是後來我得到了各種語法錯誤,所以我有點在這裏迷路了。

有人能幫我解決我在做什麼錯嗎?歡迎所有提示!

ps:我目前正在對SQLite進行測試,但最終還是應該在MySQL上工作。如果有差異,那當然也是非常有趣的知道。

+1

嘗試先選擇喜歡 - > SELECT t1.created,t1.property_id,t1.requesting_user_id ...它應該在基於https://dev.mysql.com/doc/refman/5.1/en/example-maximum-column-group-row的MySQL中工作。 html – 2015-04-02 20:23:53

+0

@AleksandarMiladinovic - 就是這樣。謝謝!如果你添加你的評論作爲答案,我可以接受它。 – kramer65 2015-04-03 05:25:23

+0

不客氣。我很高興我可以幫助:) – 2015-04-03 08:17:29

回答

相關問題