[英]mysql update one table from another
I have a massive database over over 2.7 million rows. 我有一个超过270万行的海量数据库。 It contains data on uk property prices.
它包含英国房地产价格的数据。
The first Table is called PricePaid And has a column called Price and Loc4. 第一个表称为PricePaid,并具有称为Price和Loc4的列。
Now I am trying to get the average for each year grouped by loc4 and update another tabel called PricePaidByCounty. 现在,我试图获取按loc4分组的每年的平均值,并更新另一个名为PricePaidByCounty的表格。
I have created this SQL statement : 我创建了以下SQL语句:
INSERT PricePaidByCounty (County, Avg2013)
SELECT Loc4,
Avg(Price) as AvgPrice2013 FROM PricePaid WHERE Date Like '%2013%'
Group BY Loc4
This works fine for inserting initial row but I want to use an update statement instead as I will need to run this SQL query each month. 这对于插入初始行效果很好,但是我想使用更新语句,因为我每个月都需要运行此SQL查询。
Can anyone show me how to change this Insert into an update. 谁能告诉我如何更改此插入内容以进行更新。
I am doing this as I need to quickly display average house price for each location by year. 我这样做是因为我需要按年快速显示每个位置的平均房价。 And the Database is that big I dont want to do this on the flu
而且数据库太大了,我不想在流感上这样做
Thanks 谢谢
You can update your table using following query using insert ... on duplicate key update statement ( https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html ): 您可以在重复键更新语句( https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html )上使用insert ...使用以下查询来更新表:
INSERT INTO PricePaidByCounty (County, Avg2013)
SELECT Loc4, Avg(Price) as AvgPrice2013
FROM PricePaid
WHERE Date Like '%2013%'
GROUP BY Loc4
ON DUPLICATE KEY UPDATE Avg2013=AvgPrice2013
For this to work you need to make sure that a set of (County, Avg2013) is defined as unique key. 为此,您需要确保将一组(County,Avg2013)定义为唯一键。
Looks like table PricePaidByCounty
needs three columns Country
, Year
and Average
so that while updating by year you can choose to update by particular year. 看起来表
PricePaidByCounty
需要三列Country
, Year
和Average
以便在按年更新时可以选择按特定年份更新。 Then the query would be like: 然后查询将像:
UPDATE PricePaidByCounty ppbc JOIN (SELECT Loc4,
Avg(Price) as AvgPrice FROM PricePaid WHERE Date Like '%2013%'
Group BY Loc4) ap SET ppbc.Average = ap.AvgPrice WHERE ppbc.Country = ap.Loc4 AND ppbc.Year = 2013;
This can be enhanced to group by Loc4
and Year
and directly update to PricePaidByCounty
. 可以将其增强为
Loc4
和Year
组,并直接更新为PricePaidByCounty
。 It may run for days as you have multiple records. 由于您有多个记录,它可能会运行几天。 :D
:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.