加入两个不同的连接查询输出

时间:2014-09-03 09:55:19

标签: mysql

我的第一次加入是

select
 SD.id,
 SD.Scenario,
 PR.Type,
 PR.StationName,
 max(if(PARAM = 'minH', Value, ' ')) as 'minH',
 max(if(PARAM = 'maxH', Value, ' ')) as 'maxH',
 psd.Station_Id,
 psd.Min_OL,
 psd.Max_OL from sgwebdb.param_reference as PR
     Inner join
 sgwebdb.scenario_data as SD ON PR.Param_Id = SD.Param_Id
     INNER JOIN
 sgwebdb.qualicision_detail as Q ON SD.SCENARIO = Q.Alternative
     INNER JOIN
 sgwebdb.pump_station_detail as psd ON psd.Station_Id = PR.Station_Id
  where
  PR.Type = 'Pump' and Q.Alternative = 'C'
 GROUP BY PR.Id;

OutPut是:

Output

另一个加入是:

SELECT *
FROM sgwebdb.pump_station_data t1
INNER JOIN
(
  SELECT Station_id,  MAX(lastupdate) as lastupdate
  FROM sgwebdb.pump_station_data
  GROUP BY Station_id
) t2
  ON t1.Station_id = t2.Station_id
  AND t1.lastupdate = t2.lastupdate

输出是 Output2

我想要的输出是,我需要加入两个查询并从第二个连接中获取daily_abstraction列。 就像下面一样 期望的输出:

-----------------------------------------------------------------------------------------------------
ID  |  Scenario |  Type |  StationName | MinH | MaxH | Station_Id | Min_OL | Max_OL|Daily_Abstraction
-----------------------------------------------------------------------------------------------------

2 个答案:

答案 0 :(得分:2)

喜欢 -

SELECT * FROM
(select_query1) q1 JOIN (select_query2) q2 
ON q1.someColumn = q2.someColumn


<强> QUERY

  select q1.ID  ,  q1.Scenario, 
    q1. Type, q1.StationName ,
    q1. MinH, q1.MaxH ,
    q1.Station_Id, q1.Min_OL, 
    q1.Max_OL, q2.Daily_Abstraction
    from
    (select
     SD.id,
     SD.Scenario,
     PR.Type,
     PR.StationName,
     max(if(PARAM = 'minH', Value, ' ')) as 'minH',
     max(if(PARAM = 'maxH', Value, ' ')) as 'maxH',
     psd.Station_Id,
     psd.Min_OL,
     psd.Max_OL from sgwebdb.param_reference as PR
         Inner join
     sgwebdb.scenario_data as SD ON PR.Param_Id = SD.Param_Id
         INNER JOIN
     sgwebdb.qualicision_detail as Q ON SD.SCENARIO = Q.Alternative
         INNER JOIN
     sgwebdb.pump_station_detail as psd ON psd.Station_Id = PR.Station_Id
      where
      PR.Type = 'Pump' and Q.Alternative = 'C'
     GROUP BY PR.Id) q1

    JOIN

    (SELECT t1.Daily_Abstraction,t1.Station_id 
    FROM sgwebdb.pump_station_data t1
    INNER JOIN
    (
      SELECT Station_id,  MAX(lastupdate) as lastupdate
      FROM sgwebdb.pump_station_data
      GROUP BY Station_id
    ) t2
      ON t1.Station_id = t2.Station_id
      AND t1.lastupdate = t2.lastupdate
    ) q2

    on q1.Station_Id=q2.Station_Id;

答案 1 :(得分:0)

如果Station_Id是唯一的,您可以将第二个语句加入第一个语句,方法与在第二个语句中加入t2的方式相同。