Q:

MySQL Order by count of rows

I have a table msg like
msg_id|from|to|msg|

Now i want to select All msg_id whom i have most  msg with.
eg.
If i want to select my top 2 messengers in desc order(i am with id=2)
msg_id|from|to|msg|
1       2    3 Hi
2       2    3 Hi
3       2    4 Hi
4       3    2 Hi
5       3    4 Hi
6       4    2 Hi
7       3    2 Hi
8       1    2 Hi
9       2    4 Hi
10      3    2 Hi

The query will give me 
3 (since total msg =5 )
4  (since total msg =4 )

A:

If I'm understanding your question correctly, you need to use UNION ALL to combine your to and from columns (since either could contain the id you're looking for).  Then you can order by the COUNT descending:
select id
from (
  select `to` id, `from` contact
  from msg
  union all
  select `from`, `to`
  from msg
  ) t
where contact = 2
group by id
order by count(1) desc
limit 2

SQL Fiddle Demo

