您的位置:首頁/技術文章
文章詳情頁

mysql連表排序

【字号: 作者:豬豬瀏覽:117日期:2022-06-20 17:57:13

問題描述

表Aid info 1message12message23message3表Bid goods_id1 11 22 33 4

AB表id連表,查詢結果根據B表的相同id個數排序,例如id=1的在B表有兩個,排在前面,id=2和id=3的只有一個,排在后面,請問mysql排序語句order by該怎么寫?

問題解答

回答1:

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回答2:

說一下可用的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.idorder by c.cnt, a.id回答3:

假如數據量會多的話。要是我,就重新考慮需求的合理性。能推掉就推掉。推不掉就在,a表加多一個冗余字段 goods_count。然后建聯合索引。

相關文章:
国产综合久久一区二区三区