Rumah > Soal Jawab > teks badan
表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该怎么写?
PHP中文网2017-04-17 15:00:36
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
伊谢尔伦2017-04-17 15:00:36
说一下可用的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