MySQL Query多对一连接

时间:2010-12-09 00:47:00

标签: mysql

我有一个我正在使用的查询,它使用来自多个列的ID来引用一个表来获取有关该ID的信息。这是代码:

SELECT `Events`.EventID,
       `Events`.AssociationID,
       `Events`.Association2ID,
       `Events`.Association3ID,
       `Events`.Association4ID,
       `Events`.Association5ID,
       `Events`.DateFrom,
       `Events`.DateTo,
       `Events`.EventName,
       `Events`.VenueID,
       `Events`.TestnTune,
       `Events`.ShownShine,
       `Events`.SpecialInfo,
       `Events`.OtherInfo,
       `Events`.Rating,
       `Events`.EventOverlay,
       `Events`.HavePictures,
       `Events`.IncludeInSchedule,
       `Events`.EventURL,
       Associations.Active,
       Associations.Acronym,
       Associations.OrgName,
       Associations.WebURL,
       Associations.LogoURL,
       Venues.LocationName,
       Venues.Location,
       Venues.longetude,
       Venues.latitude,
       Venues.Directions,
       Venues.SitePros,
       Venues.SiteCons,
       Venues.BasicInfo,
       Venues.SiteRating,
       Venues.HostedEvents,
       Venues.CurrentWeather
     FROM `Events`
LEFT JOIN Associations ON `Events`.AssociationID = Associations.AssociationID 
                      AND `Events`.Association2ID = Associations.AssociationID 
                      AND `Events`.Association3ID = Associations.AssociationID 
                      AND `Events`.Association4ID = Associations.AssociationID 
                      AND `Events`.Association5ID = Associations.AssociationID
LEFT JOIN Venues ON `Events`.VenueID = Venues.VenueID
    WHERE `Events`.DateFrom >= NOW()

我想要做的是捕获有关每个ID的详细信息。我无法弄清楚这是怎么做到的。例如:

For Association2ID:
    Associations.Active,
    Associations.Acronym,
    Associations.OrgName,
    Associations.WebURL,
    Associations.LogoURL

For Association3ID
    Associations.Active,
    Associations.Acronym,
    Associations.OrgName,
    Associations.WebURL,
    Associations.LogoURL,
etc.

1 个答案:

答案 0 :(得分:0)

如果您将JOIN更改为

LEFT JOIN Associations ON 
Associations.AssociationID IN (`Events`.AssociationID,
                               `Events`.Association2ID, 
                               `Events`.Association3ID, 
                               `Events`.Association4ID, 
                               `Events`.Association5ID)

这会改善一些事情吗?

您可能还应考虑将事情重组为first normal form

不是为潜在的AssociationID保留5列,而是建模这个多对多关系id的常规方法,以使用包含两列AssociationIDEventId的联结表