Help - Search - Members - Calendar
Full Version: can a field in mysql contain a formula?
Invision Power Services > Community Forums > Community Web Design and Coding
Trel
can I have a feild in a mysql table that will always contain the current average of two other fields in that table?
Chad
As far as I know, you can't do this with MySQL alone.
But you can use PHP + MySQL queries to get the average of what you want and store that average in a table.

But as far as I know, MySQL can't do this directly.

Chad
Phil Mossop
No, you can't use a database like Excel if that's what you're thinking. A database is 'static' if you like, the data you enter cannot effect data in another field and row. original.gif
Trel
so realisticly I'd update that column when I update one or both of the other rows then?
Chad
It would be completely possible to write a PHP extension to use an Excel datasheet, right?

QUOTE(Trel @ Apr 3 2005, 08:30 AM)
so realisticly I'd update that column when I update one or both of the other rows then?
*


Yes, each time you update one or both rows, the column needs to be updated, as you said.

Chad
Trel
ok so here's a different question

can a query look like this

CODE
UPDATE `table` set `field3` = (`field1`+`field2`)\2


or is that invalid syntax?
Chad
You can do math inside a query, but I am not sure if that one is possible.
Before actually writing a script using it, try it in PHPMyAdmin for syntax.

Chad
Trel
ouch, to make it work how I want, I had to use this query

SQL
UPDATE `sites` SET `rank` = FLOOR(((`hits_in`+`hits_out`)/2)+0.5)
Brendon Koz
Rather than actually storing the data, would it be more efficient to do the math on the actual query when you NEED the data?

Such as:
CODE
SELECT FLOOR(((`hits_in`+`hits_out`)/2)+0.5) AS Average FROM sites;


...and then your WHERE clause etc, etc...

-edit-
...forgot to close the code tag. tongue.gif
Trel
not really as I plan to use that data in other ways (such as ordering by it when selecting)
Brendon Koz
You can still order by it during the select, but it would be faster if the field were not calculated during the select. Just figured it'd be easier. wink.gif I just hope that those two fields don't change often on you.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.