开发者

MySQL Query Problem - Joins and Grouping

Im reposting this problem in a simpler fashion, as I was getting comments about it being too specific:

Based on the following travel model relationships, how do I sel开发者_StackOverflow中文版ect all Itineraries with at least one Stop in Region X, and still have the query return ALL the Stops for that Itinerary, even if the other Stops are in Regions other than X

I'm using Php and MySQL and Doctrine.

Region HAS MANY Country
Country HAS MANY Area
Area HAS MANY Property
Property HAS MANY Stop 
Itinerary HAS MANY Stop


SELECT i.*
     , sa.*
FROM Itinerary AS i
  JOIN Stop AS sa
    ON i.ItineraryId = sa.ItineraryId
WHERE EXISTS
      ( SELECT *
        FROM Stop AS s
          JOIN Property AS p
            ON p.PropertyId = s.PropertyId
          JOIN Area AS a
            ON a.AreaId = p.AreaId
          JOIN Country AS c
            ON c.CountryId = a.CountryId 
          JOIN Region AS r
            ON r.RegionId  = c.RegionId
        WHERE s.ItineraryId = i.ItineraryId
          AND r.Name = @X
      ) 


SELECT * from Itinerary where id in(
SELECT DISTINCT Itinerary.id
FROM Itinerary
LEFT JOIN Stop on Itinerary.something = Stop.something
LEFT JOIN Property ON Stop.something=Property.something
LEFT JOIN Area ON Area.something=Property.something
LEFT JOIN Country ON Country.something=Area.something
LEFT JOIN Region ON Region.something = Country.something
WHERE Region.something = X)


select * from Itinerary where EXISTS (select * from Itinerary where stop = X);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜