I am trying to find a MySQL query that will find distinct values in a particular field, count the number of occurrences of that value in 2 fields (1_user, 2_user) and then order the results by the count.
example db
+------+-----------+-----------+ | id | 1_user | 2_user | +------+-----------+-----------+ | 1 | 2 | 1 | | 2 | 3 | 2 | | 3 | 8 | 7 | | 4 | 1 | 8 | | 5 | 2 | 8 | | 6 | 3 | 8 | +------+-----------+-----------+
expected result
user count ----- ----- 8 4 2 3 3 2 1 2
The Query
Explanation
List all the users in the first column.
Combine them with the users from the second column.
The trick here is the UNION ALL which preserves duplicate values.
The rest is easy — select the results you want from the subquery:
aggregate by user:
and prescribe the order: