I’m looking to update certain rows based on specific criteria based on other rows. Lets say the table looks like this:
COLUMNS: time type genre doubles triples
ROW 1: 2010.06.21 12:00 1 1 0 0
ROW 2: 2010.06.21 12:00 1 2 0 0
ROW 3: 2010.06.21 12:00 1 1 0 0
ROW 4: 2010.06.21 12:00 2 3 0 0
ROW 5: 2010.06.22 12:00 2 2 0 0
ROW 6: 2010.06.22 12:00 2 3 0 0
ROW 7: 2010.06.22 12:00 1 1 0 0
I’m looking to update the doubles and triples columns based on the following rules:
1) Only look to update rows where the time=time and type=type between rows (e.g. Rows 1,2,3 and rows 5 & 6).
2) Next count the # of different genre‘s between those rows and if there are two different genres then change the doubles column to 1, or if there are three then change the triples column to 1. SO for example in the table above rows 1,2,3 would have doubles=1 because between the three rows there are two different genres. Rows 5 and 6 would also have doubles=1 because there is again two different genres between the rows. Doubles can =1 and triples can =1 but not both.
Now, I could write up some PHP based on these rules pretty easily I think, but I’m wondering if there is a way to do it all in mysql? It seems like I’m always surprised the amount you can do from a SQL statement.
Maybe something like (two different statements for the doubles and triples column):
Doubles – UPDATE myTable SET (doubles=1) WHERE time=time AND type=type … but then how would you account for rule #2 above (counting number of rows with unique genres).
Is this possible in mysql or is PHP just the right way to go here?
Thanks in advance
Sure, you can do it in one query. Using this sample table:
The update statement should join to the GROUPed form to get the doubles and triples.