MySQL查询问题 - 加入和分组

时间:2011-08-23 20:40:21

标签: php mysql join doctrine

我以更简单的方式重述这个问题,因为我得到的评论过于具体:

根据以下旅行模式关系,如何在区域 X <中选择至少一个停止的所有行程 < / em>,仍然有查询返回行程的所有停止,即使其他停止位于区域< / strong>除了 X

我正在使用Php和MySQL以及Doctrine。

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

3 个答案:

答案 0 :(得分:1)

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
      ) 

答案 1 :(得分:0)

从行程中选择* EXISTS(从行程中选择*停止= X);

答案 2 :(得分:0)

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)