简体   繁体   中英

MySql query returning entire table with possible values from a second table

I have 2 tables:

event_categories containing:

event_category_id, event_category

Sample data:

1, Tennis
2, Volleyball
3, Boxing
4, Skating

Then I have a table that joins users that might possibly be linked to any of these categories.

users_event_categories containing

user_id, event_category_id

Sample data:

1223, 2
1223, 4
5998, 2

I need a query that returns ALL event categories, and returns if a user has that category linked.

So if I query with the user_id 1223 my result would be:

1, Tennis, 0
2, Volleyball, 1
3, Boxing, 0
4, Skating, 1

Or a query with user_id 4444 would return:

1, Tennis, 0
2, Volleyball, 0
3, Boxing, 0
4, Skating, 0

This would work if you only want data about one particular user

select ec.event_category_id, ec.event_category, if(uec.user_id is null, 0, 1) 
from event_categories ec 
    left join users_event_categories uec
        on uec.event_category_id = ec.event_category_id and uec.user_id = 1223
select tn2.user_id,event_category,count(event_category) as total from table_name1 tn1
inner join table_name2 tn2 on tn1.event_category_id = tn2.event_category_id
where tn2.user_id = 4444
group by event_category

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