简体   繁体   中英

SQL count many-to-many relations in common

i have a sql problem with this schemas :

table user(id, name) table page(id, name) table page_user(id_page, id_user)

one page can be liked by multiple users and one user can like multiple pages

i would like to select all users in my table with a column with the number of liked page in common with some fixe user like : id_user | page_in_common_with_user_#id#_count id_user | page_in_common_with_user_#id#_count

Assuming that "liked page" refers to the page_user table, then you can use a self join:

select pu.id_user, count(pux.id_page) as PagesInCommonWithX
from page_user pu left join
     page_user pux
     on pu.id_page = pux.id_page and
        pux.id_user = $x
group by pu.id_user;

you can do it easily by this query:

select id_user , count(id_page)
from user left outer join page_user on user.id = page_user.id_user
group by id_user

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