数据库内连接GROUP BY查询外键表数据行的总数
最近看了看SQL,刚好遇到这个问题。
INNER JOIN [外键表] ON [主键表] 内链接,用 GROUP BY 分组外键数据,COUNT(*)计算该外键数据总行数,最后用 ORDER BY 排序,DESC 关键字表示降序,想让数据输出升序省略DESC关键字即可
代码如下:
SELECT UserMessageBoard.CategoriesId,MessageBoardCategories.CategoriesTitle,COUNT(*) AS CategoriesSum
FROM MessageBoardCategories
INNER JOIN UserMessageBoard
ON UserMessageBoard.CategoriesId = MessageBoardCategories.CategoriesId
GROUP BY UserMessageBoard.CategoriesId,MessageBoardCategories.CategoriesTitle
ORDER BY CategoriesSum DESC
查询结果如下:
主键表(MessageBoardCategories)数据如下:
外键表(UserMessageBoard)数据如下:
有问题请留言!
相关推荐
敏敏张 2020-11-11
数据库之扑朔迷离 2020-08-18
北桥源木 2020-08-15
ssjdoudou 2020-08-09
boredbird 2020-08-07
InJavaWeTrust 2020-06-21
QianChia 2020-06-14
窃破天道 2020-06-12
KaiZhaoKZ 2020-05-30
Lius 2020-05-27
Rain 2020-04-15
dreamhua 2020-04-30
dayi 2020-04-29
iflreey 2020-04-29
bluetears 2020-04-18
neverstopforcode 2020-04-15
chenjiazhu 2020-03-28
aweilark 2020-03-06
imacoder 2020-02-23