如何将带有内连接语句的Sql查询转换为带有Where语句的sql查询(语句中没有内连接)

时间:2009-12-05 15:52:54

标签: sql join

我使用Qbe在访问中生成了以下sql查询代码并将其转换为sql。但是,我想要证明我没有帮助,所以我打算取出所有内部连接语句并用WHERE语句替换它们。我该如何解决这个问题。请解释并提供答案。谢谢。

SQL查询:

SELECT Entertainer.EntertainerID, Entertainer.FirstName, Entertainer.LastName, 
       Booking.CustomerID, Booking.EventDate, BookingDetail.Category, BookingDetail.Duration, 
       Speciality.SpecialityDescription, EntertainerSpeciality.EntertainerSpecialityCost

FROM (Entertainer INNER JOIN (Booking INNER JOIN BookingDetail ON 
                              Booking.BookingID=BookingDetail.BookingID) ON   
      Entertainer.EntertainerID=BookingDetail.EntertainerID) 
INNER JOIN (Speciality INNER JOIN EntertainerSpeciality ON 
            Speciality.SpecialityID=EntertainerSpeciality.SpecialityID) ON 
Entertainer.EntertainerID=EntertainerSpeciality.EntertainerID

WHERE (((Entertainer.EntertainerID)=[Enter EntertainerID]));

2 个答案:

答案 0 :(得分:4)

这是我见过的最奇怪的JOIN声明。这是您的查询转换为ANSI-89语法:

SELECT e.entertainerid, 
       e.firstname, 
       e.lastname, 
       b.customerid, 
       b.eventdate, 
       bd.category, 
       bd.duration, 
       s.specialitydescription, 
       es.entertainerspecialitycost
  FROM Entertainer e,
       BookingDetail bd,
       Booking b,
       EntertainerSpeciality es,
       Speciality s
 WHERE e.entertainerid = bd.entertainerid
   AND b.bookingid = bd.bookingid
   AND e.entertainerid = es.entertainerid
   AND s.specialityid = es.specialityid
   AND e.entertainerid = [Enter EntertainerID]

此处您的原始查询已清除语法 - 它应该有助于更容易地查看常用信息:

SELECT e.entertainerid, 
       e.firstname, 
       e.lastname, 
       b.customerid, 
       b.eventdate, 
       bd.category, 
       bd.duration, 
       s.specialitydescription, 
       es.entertainerspecialitycost
  FROM ENTERTAINER e
  JOIN BOOKINGDETAIL bd ON bd.entertainerid = e.entertainerid
  JOIN BOOKING b ON b.bookingid = bd.bookingid
  JOIN ENTERTAINERSPECIALITY es ON es.entertainerid = e.entertainerid
  JOIN SPECIALITY s ON s.specialityid = es.specialityid
 WHERE e.entertainerid = ?

不同之处在于ANSI-89语法包括WHERE子句中的连接条件以及实际的过滤条件。要突出显示,ANSI-92:

  FROM ENTERTAINER e
  JOIN BOOKINGDETAIL bd ON bd.entertainerid = e.entertainerid

... vs ANSI-89:

  FROM ENTERTAINER e,
       BOOKINGDETAIL bd
       ,... -- omitted for purpose of example
 WHERE e.entertainerid = bd.entertainerid

首选ANSI-92语法:

  • ANSI-89在各种数据库中没有始终如一地实现LEFT JOIN语法,因此语句是可移植的
  • ANSI-92提供更强大的JOIN(IE:x ON x.id = y.id AND x.col IS NOT NULL)
  • ANSI-92更易于阅读,将连接条件与实际过滤条件分开

答案 1 :(得分:0)

想做的事情很奇怪(正如评论者所说,INNER JOIN通常更好,并且应用机械转换证明什么都没有),但并不困难。每个INNER JOIN都可以机械转换为WHERE,如下所示:

而不是每个双向内连接A INNER JOIN B ON (cond1) WHERE (cond2)

将其重写为A, B WHERE (cond1) AND (cond2)

无论表AB以及条件cond1cond2可能是什么。