简体   繁体   English

MySQL查询返回整个表与第二个表的可能值

[英]MySql query returning entire table with possible values from a second table

I have 2 tables: 我有2张桌子:

event_categories containing: event_categories包含:

event_category_id, event_category 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 users_event_categories包含

user_id, event_category_id 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: 因此,如果我使用user_id 1223查询,我的结果将是:

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

Or a query with user_id 4444 would return: 否则,使用user_id 4444的查询将返回:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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