首页 > mysql连表排序

mysql连表排序

表A
id      info   
1        message1
2        message2
3        message3


表B
id         goods_id
1            1
1            2
2            3
3            4

AB表id连表,查询结果根据B表的相同id个数排序,例如id=1的在B表有两个,排在前面,id=2和id=3的只有一个,排在后面,请问mysql排序语句order by该怎么写?


select A.id, A.info, count(B.goods_id) from A inner join B on A.id = B.id group by A.id order by count(B.goods_id) desc

假如数据量会多的话。
要是我,就重新考虑需求的合理性。能推掉就推掉。
推不掉就在,a表加多一个冗余字段 goods_count。然后建联合索引。


说一下可用的sql语句,性能上不是太好,多了一次对表b的查询。

select a.*, b.*
from a
  inner join b on a.id = b.id
  inner join (
    select id, count(*) as cnt
    from b
    group by id
  ) c on a.id = c.id
order by c.cnt, a.id
【热门文章】
【热门文章】