I need a mysql query which will select all rows that contain “joe” in either the “to” or “from” column. It needs to be distinct among the “to” and “from” columns, which means that it does not matter what order the names appear in. i.e. “joe”, “bob” should be treated as the same as “bob”, “joe”. If there are duplicates among a pair of names, choose the one with the max id. The final table should also be sorted by id descending. For example, running the query on the below table:
Before:
id to from
---|-----|------
1 | joe | bob |
2 | bob | hal |
3 | joe | joe |
4 | sue | joe |
5 | bob | bob |
6 | bob | joe |
7 | hal | hal |
8 | joe | bob |
After:
id to from
---|-----|------
8 | joe | bob |
4 | sue | joe |
3 | joe | joe |
Try a GROUP BY where you group by (from, to) sorted in alphabetical order:
See it working online: sqlfiddle