|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Updating Table
I have two tables with following content:
TABLE_A |-ID-|-GROUPID------|-MARK--| |-1--|-------1-------|--65.54-| |-2--|-------1-------|--75.60-| |-3--|-------1-------|---58---| |-4--|-------2-------|--55.78-| |-5--|-------3-------|--88.00-| |-6--|-------3-------|--56.70-| |-7--|-------4-------|--66.47-| and so on, many enteries TABLE_B |--GROUPID------|--AVRG_MARK------| |-------1--------|-----0.000---------| |-------2--------|-----0.000---------| |-------3--------|-----0.000---------| |-------4--------|-----0.000---------| and so on ........ I want to update TABLE_B's AVRG_MARK column where TABLE_B.GROUPID = TABLE_A.GROUPID so that TABLE_B's AVRG_MARK contains averages. For example, 1st row in TABLE_B will get updated and contain: |-1-|---66.88---| where 66.88 = (65.54+75.60+58)/3 Those 3 numbers in brackets come from TABLE_A's MARK column and I devide by 3 since there are 3 enteries I want to do this for the whole TABLE_B. Can you help me out guys, I'm a bit stuck. I've built my database tables using MySQL. |
|
#2
|
||||
|
||||
|
I'm curious, why are you storing the average mark in a database?
It can be calculated quickly from a query. I think the following should achieve TABLE_B: SELECT GROUPID, AVG(mark) FROM TABLE_A GROUP BY GROUPID Keep in mind, my query doesn't help you store it in the database. I would use this everywhere you would have been using SELECT * FROM TABLE_B |
|
#3
|
|||
|
|||
|
Quote:
My TABLE_B actually contains 2 more columns (Pref_1, Pref_2) that I need to use in order to perform a selection algorithm based on a highest average mark. I've posted this question on another forum and this is the answer that I've received: update table_b set avrg_mark = x.av from table_b join (select group_id, ave(mark) av from table_a group by group_id) x on table_b group_id = x.group_id group by group_id) However, I have no clue what this does, do you ? |
|
#4
|
|||
|
|||
|
It's using a subquery to create a 'table' called x containing the average you need. That table is being joined to table_b, so you can then use that average to update your average field in table_b.
If possible, though (and I don't know how your pref_* fields interact with your average, but I'll take your word for it if you say it's not), you shouldn't store the results of calculations like that in your db. Like MadCowDzz said, you can calculate averages on the fly pretty easily. If you store them statically, though, you have to constantly re-run and update your rows to keep it current.
__________________
"A pawn is the most important piece on the chessboard -- to a pawn" |
![]() |
| Viewing: Dev Articles Community Forums > Databases > MySQL Development > Updating Table |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|