MySQL子查询问题

时间:2010-12-09 08:13:02

标签: mysql

我正在努力完成某些事情并且无法确定是否可以完成。我有一个表“事件”,其中包含事件信息。在该表中是赞助该事件的协会的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,
Associations.AssociationID,
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()

2 个答案:

答案 0 :(得分:0)

看起来你正试图通过使用几个1-n关系来建模多对多关系,并将它们命名为association1,association2等......这可能不是一个好主意。

创建一个名为EventToAssociation(或类似)的新实体,为这两个事件和关联保存外键。然后,您的联接将更容易创建。

在示例查询中,这将显示为:

SELECT *
FROM Event e
JOIN EventToAssociation e2a ON e.EventID = e2a.EventID
JOIN Association a ON e2a.AssociationID = a.AssociationID

如果无法更改架构,那么您必须多次将Association加入Event,例如

SELECT *
FROM Event e
LEFT OUTER JOIN Associations a1 ON e.AssociationID = a1.AssociationID
LEFT OUTER JOIN Associations a2 ON e.Association2ID = a2.AssociationID
LEFT OUTER JOIN Associations a3 ON e.Association3ID = a3.AssociationID
LEFT OUTER JOIN Associations a4 ON e.Association4ID = a4.AssociationID
LEFT OUTER JOIN Associations a5 ON e.Association5ID = a5.AssociationID

答案 1 :(得分:0)

您所做的每个联接都在您的事件表和相同的关联表之间。这就像一个AND条件。

尝试使用别名:

LEFT JOIN Associations Asso1 ON `Events`.AssociationID = Asso1.AssociationID
LEFT JOIN Associations Asso2 ON `Events`.Association2ID = Asso2.AssociationID