MySQL通过多个外键查询

时间:2017-01-11 11:04:39

标签: mysql join

基本上,我需要做的是计算每个赞助商(来自表赞助商)参与每个Type_name(来自Event_types)的次数。我想通过多个JOIN查询来完成它,但我似乎很快就迷路了。

这是我的数据库的图片。

Picture of SQL database

提前致谢。

P.S,忽略数据库名称,本地服务器不允许我创建超过5个单独的数据库,因此不得不使用现有的数据库进行我的边项目:)

3 个答案:

答案 0 :(得分:0)

select c.Club, e.Event_Type, count(sr.Sponsor) as totalsponsoring
from Sponsoring sr
join Sponsors s on s.Sponsor_name = sr.Sponsor
join Clubs c on c.Club = sr.Club
join Events e on e.Club = c.Club
group by sr.Sponsor

答案 1 :(得分:0)

select 
    events.event_type,
    sponsoring.sponsor,
    count(sponsing.id) 
from sponsoring 
join events on sponsoring.club = events.club
group by 
    events.event_type, 
    sponsoring.sponsor

如果你需要俱乐部桌子:

select 
    events.event_type,
    sponsoring.sponsor,
    count(sponsing.id) 
from sponsoring 
join clubs on sponsoring.club = clubs.club
join events on clubs.club = events.club
group by 
    events.event_type, 
    sponsoring.sponsor

答案 2 :(得分:0)

我设法对" connect"进行了2次单独的查询。带赞助商的俱乐部和俱乐部的Event_types。我如何将它们合二为一?

SELECT Sponsors.Sponsor_name as Sponsor, Clubs.Club as Club FROM Sponsoring JOIN Sponsors ON Sponsoring.Sponsor=Sponsor_name JOIN Clubs ON Sponsoring.Club=Clubs.Club;
SELECT Clubs.Club as Club, Event_types.Type_name as Typename FROM Events JOIN Clubs on Events.Club=Clubs.Club JOIN Event_types ON Events.Event_type=Event_types.Type_name;