加入两个查询

时间:2013-08-26 07:51:12

标签: sql

select a.Enquiry_Id,a.Ckeck_In,a.check_Out,a.Hotel_Name,a.Meal_Plan,a.Room_Type,a.Occupancy_Type,a.Room_QT,a.Adults from Accomodation a 
where a.Enquiry_Id = 74

select q.Enquiry_Id,q.Start,q1.Stay_At from Quick_Plan q,Quick_Plan q1 where q.Enquiry_Id = 74 and q1.Enquiry_Id = 74 and q.Stay_At = q1.Start

第一次查询的结果是

74  2013-08-03  2013-08-04  ADS CP          deluxe  Double  1   2 

,第二个查询的结果是

74  Ahmedabad   Agra

我想合并这两个查询,以便得到像

这样的结果
74  2013-08-03  2013-08-04  ADS CP          deluxe  Double  1   2 Ahmedabad Agra

3 个答案:

答案 0 :(得分:0)

在您的情况下,最简单的方法是使用CTE,因为它们不需要太多修改。

;WITH FirstCTE AS
(
    SELECT    a.Enquiry_Id, 
              a.Ckeck_In,
              a.check_Out,  
              a.Hotel_Name, 
              a.Meal_Plan,
              a.Room_Type,
              a.Occupancy_Type,
              a.Room_QT,
              a.Adults 
    FROM      Accomodation a 
    WHERE     a.Enquiry_Id = 74
),
SecondCTE AS
(
    SELECT    q.Enquiry_Id,
              q.Start,
              q1.Stay_At 
    FROM      Quick_Plan q,
              Quick_Plan q1 
    WHERE     q.Enquiry_Id = 74 
              and q1.Enquiry_Id = 74 
              and q.Stay_At = q1.Start
)

SELECT * 
FROM   FirstCTE F
       JOIN SecondCTE S
       ON F.Enquiry_Id = S.Enquiry_Id

我认为正确的方法是:

SELECT    a.Enquiry_Id, 
          a.Ckeck_In,
          a.check_Out,  
          a.Hotel_Name, 
          a.Meal_Plan,
          a.Room_Type,
          a.Occupancy_Type,
          a.Room_QT,
          a.Adults ,
          q.Start,
          q1.Stay_At 
FROM      Accomodation a 
          JOIN Quick_Plan q
              ON a.Enquiry_Id = q.Enquiry_Id
          JOIN Quick_Plan q1 
              ON q.Enquiry_Id = q1.Enquiry_Id 
              and q.Stay_At = q1.Start
WHERE     a.Enquiry_Id = 74

答案 1 :(得分:0)

假设a.Enquiry_Id和q.Enquiry_Id是您用来加入的密钥,

 SELECT a.Enquiry_Id, a.Ckeck_In, a.check_Out, a.Hotel_Name, a.Meal_Plan,  a.Room_Type, a.Occupancy_Type, a.Room_QT, a.Adults,q.Start, q1.Stay_At 
 FROM Accomodation a 
 INNER JOIN Quick_Plan q ON a.Enquiry_Id = q.Enquiry_Id
 INNER JOIN Quick_Plan q1 ON q1.Enquiry_Id = q.Enquiry_Id
 WHERE a.Enquiry_Id = 74 AND
    q.Stay_At = q1.Start

答案 2 :(得分:0)

select
a.Enquiry_Id,
a.Ckeck_In,
a.check_Out,
a.Hotel_Name,
a.Meal_Plan,
a.Room_Type,
a.Occupancy_Type,
a.Room_QT,
a.Adults,
q.Enquiry_Id,
q.Start,
q1.Stay_At 
from 
Accomodation a, 
Quick_Plan q, 
Quick_Plan q1 
where 

q.Enquiry_Id = 74 
and q1.Enquiry_Id = 74 
and q.Stay_At = q1.Start 
and a.Enquiry_Id = 74

试试这个