如何在连接中转换此子查询?
How to convert this subquery in a join?
使用 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
不幸的是,这 returns 是一个错误 ambiguous column name: created
。所以我把 t1.
或 t2.
放在一些创建的东西之前搞砸了,但后来我遇到了各种语法错误,所以我有点迷路了。
任何人都可以帮助我解决我在这里做错的事情吗?欢迎所有 tips!
ps:我目前正在 SQLite 上对此进行测试,但最终它应该也适用于 MySQL。如果有什么不同,当然也很想知道。
第一个 select 应该是这样的:
SELECT t1.created, t1.property_id, t1.requesting_user_id, type, response...
你做的其他一切都正确...
基于https://dev.mysql.com/doc/refman/5.1/en/example-maximum-column-group-row.html ...
GL
使用 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
不幸的是,这 returns 是一个错误 ambiguous column name: created
。所以我把 t1.
或 t2.
放在一些创建的东西之前搞砸了,但后来我遇到了各种语法错误,所以我有点迷路了。
任何人都可以帮助我解决我在这里做错的事情吗?欢迎所有 tips!
ps:我目前正在 SQLite 上对此进行测试,但最终它应该也适用于 MySQL。如果有什么不同,当然也很想知道。
第一个 select 应该是这样的:
SELECT t1.created, t1.property_id, t1.requesting_user_id, type, response...
你做的其他一切都正确...
基于https://dev.mysql.com/doc/refman/5.1/en/example-maximum-column-group-row.html ...
GL