给定两个相关表,如何确定最常见的关系?

时间:2018-08-07 17:02:18

标签: sql mariadb rds

给出了3个表格:用户,书籍,book_users,我如何确定什么是公共书籍?

users: id, first_name, last_name
books: id, name
books_users: book_id, user_id

Designer输出,类似于:

book | count
radBookName | 22
SemiRad | 22

谢谢

1 个答案:

答案 0 :(得分:3)

您似乎想要带有JOIN子句的简单GROUP BY

SELECT b.name, count(*) as user_count
FROM books b INNER JOIN
     books_users bu
     ON bu.book_id = b.id
GROUP BY b.name;

如果一本书具有相同的用户,这将产生重复的计数,如果您想要唯一的计数,请改用count(distinct bu.user_id)