SQL Server中的连接查询问题

时间:2011-07-05 15:35:13

标签: sql sql-server tsql

以下是有效但有一些错误的查询:

SELECT dbo.Booking.Cost, 
       dbo.Booking.StatusID, 
       dbo.Account.FirstName, 
       dbo.Attendee.HelmetsPurchased AS ProductsPurchased, 
       dbo.Attendee.GaragesPurchased, 
       dbo.Attendee.SecondDriver AS [Driver Name]
  FROM dbo.Booking 
  JOIN dbo.Attendee ON dbo.Booking.EventID = dbo.Attendee.EventID 
  JOIN dbo.Account ON dbo.Booking.UserID = dbo.Account.UserID
 WHERE (dbo.Booking.EventID = 15)

输出:

output of the above query

生成的表的问题是购买的列产品,并且驱动程序名称填充了每行的文本,在这种情况下,应仅填充已Drivername和购买产品的行。与会者表中只有一行有drivername,产品购买字段填充了用户名标记,而所有其他行对drivername和产品都有空值。

2 个答案:

答案 0 :(得分:3)

而不是桌面与会者INNER JOIN,而应该LEFT JOIN。这将包括这两列也为空的行。

   SELECT b.Cost, 
          b.StatusID, 
          ac.FirstName, 
          at.HelmetsPurchased AS ProductsPurchased, 
          at.GaragesPurchased, 
          at.SecondDriver AS [Driver Name]
     FROM dbo.Booking b
LEFT JOIN dbo.Attendee at ON b.EventID = at.EventID 
LEFT JOIN dbo.Account ac ON b.UserID = ac.UserID
    WHERE b.EventID = 15

答案 1 :(得分:2)

如果您不需要驱动程序名称,以下内容可能有所帮助:

SELECT
    B.EventId,
    B.Cost,
    B.StatusID,
    A.FirstName,
    SUM(AT.HelmetsPurchased) AS ProductsPurchased,
    SUM(AT.GaragesPurchased) AS GaragesPurchased
FROM
    dbo.Booking B
INNER JOIN
    dbo.Account A ON B.UserID = A.UserID
LEFT OUTER JOIN
    dbo.Attendee AT ON B.EventID = AT.EventID 
WHERE (dbo.Booking.EventID = 15)
GROUP BY B.EventId, B.Cost, B.StatusId, A.FirstName