Filtering equivalent but not duplicate rows from MySQL result
To promote bonding in my fraternity, I'm trying to design a system where people can rate how well they know each other, then it will match up those who know each other least. This is what the table for the ratings looks like:
from_bro | to_bro | rating -------------------------- A | B | 5 B | A | 5 B | C | 2 C | B | 3 A | C | 5 C | A | 5
I want to design a query that will select the average of the ratings for each pair. So far I have this:
SELECT *, (m1.rating + m2.rating)/2 AS average FROM matches AS m1 LEFT JOIN matches AS m2 ON m1.from_bro = m2.to_bro AND m1.to_bro = m2.from_bro
That works for the most part, but it contains redundant data:
from_bro | to_bro | rating | from_bro | to_bro | rating | average ----------------------------------------------------------------- A | B | 5 | B | A 开发者_如何学C | 5 | 5.0000 B | A | 5 | A | B | 5 | 5.0000 B | C | 2 | C | B | 3 | 2.5000 C | B | 3 | B | C | 2 | 2.5000 A | C | 5 | C | A | 5 | 5.0000 C | A | 5 | A | C | 5 | 5.0000
See how the 1st and 2nd, 3rd and 4th, and 5th and 6th rows, while not duplicates, are essentially the same. Is there a way that I can filter out those redundant rows?
If the to_bro and from_bro where actually bro_id (numeric), you could add:
AND m1.from_bro_id > m2.from_bro_id
so you get only one record for each pair of bros.
If they are strings you can use:
AND STRCMP(m1.from_bro, m2.from_bro) = 1
which is a string comparison, meaning m1.from_bro > m2.from_bro
精彩评论