文章詳情頁
mysql連表排序
瀏覽:118日期: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。然后建聯合索引。
相關文章:
1. python - vscode 如何在控制臺輸入2. Python2中code.co_kwonlyargcount的等效寫法3. django - Python error: [Errno 99] Cannot assign requested address4. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?5. python小白 關于類里面的方法獲取變量失敗的問題6. javascript - webpack1和webpack2有什么區別?7. java - 線上應用,如果數據庫操作失敗的話應該如何處理?8. python小白,關于函數問題9. [python2]local variable referenced before assignment問題10. angular.js - 百度支持_escaped_fragment_嗎?
排行榜
