在where子句中使用聚合函数和group by的SQL更新查询?

时间:2011-02-06 01:38:15

标签: sql mysql

我有一张表格,其中包含住房物业的上市信息。一个属性可能在表中多次,每次列出一次。以下是相关栏目:

ListingID <- primary key
PropertyID
ListingEndDateTime

我正在尝试开发一个查询来更新表格中每个属性的最新列表的EndDateTime。该查询将EndDateTime设置为每个属性的相同值。

到目前为止,我尝试了一些方法是不成功的。我该如何撰写这样的查询?

3 个答案:

答案 0 :(得分:2)

以下假设ListingID是auto_incrementing主键:

update PropertyListing p
inner join
(
select
 max(ListingID) as ListingID,
 PropertyID
from
 PropertyListing
group by
 PropertyID
) latest on latest.ListingID = p.ListingID
set
 p.ListingEndDateTime = now();

答案 1 :(得分:0)

这允许每个日期对同一属性进行多次列出,在这种情况下将使用最新的ListingID。否则,仅最新日期就会识别该列表。

# create table PropertyListing(ListingEndDateTime Int, PropertyID Int, ListingID Int);

update PropertyListing L
inner join
(
select Max(B.ListingID) MaxListingID
FROM
(
select PropertyID, MAX(ListingEndDateTime) MaxListingEndDateTime
from PropertyListing
group by PropertyID
) A
inner join PropertyListing B
    on B.ListingEndDateTime = A.MaxListingEndDateTime and A.PropertyID = B.PropertyID
group by B.PropertyID, B.ListingEndDateTime
) C on C.MaxListingID = L.ListingID
set L.ListingEndDateTime = CURDATE() + 7;

我已经任意使用CURDATE() + 7,将其设置为所有记录所需的日期。

答案 2 :(得分:0)

可能需要调整,但是你会得到一般的想法(SQL Server 2005以后):

WITH cteMostRecent (PropertyID, ListingEndDateTime, rownum) AS
(
   SELECT PropertyID, ListingEndDateTime,
   ROW_NUMBER() OVER (PARTITION BY PropertyID ORDER BY ListingEndDateTime DESC) as rownum
   FROM MyListingTable
)  

UPDATE cteMostRecent 
SET ListingEndDateTime = someDate
WHERE rownum = 1