views:

27

answers:

3

I have a table house with fields price and area, now I want to add one more column named 'average_price'.

How could I set the average_price according to the price and area in MYSQL?

+2  A: 

Just one idea:

  • Add your column in your favorite editor/method
  • Loop through your table and define average_price value
  • Update actual row with your value

    UPDATE your_table SET average_price = price/area;

fabrik
@fabrik: is this possible with one-line sql query?
Jichao
It depends. What is average_price? If you can define it in a query i think it's possible of course.
fabrik
@fabrik: average_price is equal to price/area.
Jichao
Just updated my question. Let me know if it works.
fabrik
@fabrik: it works well, amazing.I thought it would be much more complicated.
Jichao
You're welcome :)
fabrik
+1  A: 

Hello,

You can do it with a suquery. But I don't know about performance.

UPDATE `houses` AS h
SET `avg_price` = (
    SELECT AVG(`price`)
    FROM `houses` AS h2
    WHERE h2.area == h.area
)

Or you could create a temporary table in which to put the average prices and then update.

Alin Purcaru
+1  A: 

This doesn't sound like the kind of data you should actually store, by how often you'd have to update it - once every single time you modify the house table in any way! That's a lot of unnecessary load on the database, and a whole lot of room for human error.

Instead, I recommend acquiring it on the fly through a SQL query when you need it, and never actually storing it.

Retrieving from all areas:

SELECT `area`, AVG(`price`) AS `average_price`
FROM `house`
GROUP BY `area`
ORDER BY `average_price` ASC

Retrieving from a specific area:

SELECT `area`, AVG(`price`) AS `average_price`
FROM `house`
WHERE `area` = "New York"
GROUP BY `area`
Axidos
I have never thought about the update isssue before, vote up for your advice.
Jichao
Thanks. :) As a rule of thumb, data derived from other data should generally be calculated in a query and not stored
Axidos