mysql连表排序
高洛峰
高洛峰 2017-04-17 14:58:36
0
3
705
表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该怎么写?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
Ty80
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
伊谢尔伦

Let’s talk about the available sql statements. The performance is not very good. There is one more query for table 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
伊谢尔伦

If the amount of data is large.
If it were me, I would reconsider the rationality of the demand. Push it away if you can.
If you can’t push it away, add a redundant field goods_count to table a. Then create a joint index.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!