简体   繁体   中英

How do i count the number of items in a table and join with categories from different table in mysql database

I am trying to select count distinct items from Table 2 and match it to the category list in Table 1. This is a MySQL database sample.

Table 1 (categories):

id   group_name
1      football
2      hockey
3      tennis

Table 2 (users):

id   groups
1      tennis
2      football
3      football
4      tennis
5      football
6      hockey
7      hockey

The below SQL query would do it:

SELECT A.GROUP_NAME, COUNT(DISTINCT GROUPS) CNTS 
FROM CATEGORIES A
LEFT JOIN USERS B
ON A.GROUP_NAME = B.GROUPS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM