从3个不同的表中确定每个用户的总成本

时间:2017-11-05 11:55:42

标签: mysql sql qsqlquery

我正在使用MySql中的影院预订系统(我的第一个SQL项目)。我有三张桌子:

Production (contains Title, BasicTicketPrice), 
Performance (PerformanceDate, PerformanceTime, Title) 
Booking (Email of person who booked, PerformanceDate, PerformanceTime, RowNumber). 

每个人都预订了两到三场演出门票(使用他们的电子邮件预订)。

我需要写一个查询,显示所有预订座位的价格,我需要输出RowNumber,预订人的电子邮件和计算价格。

我知道我需要加入这些表并使查询显示一个名为Calculated Price的临时列,但我不知道如何计算价格。

我试过了:

SELECT DISTINCT b.RowNumber, b.Email, pr.BasicTicketPrice 
FROM booking b, production pr performance p
WHERE p.Title=b.PerfDate*b.PerfTime*b.RowNumber;

SELECT CONCAT (PerfDate, PerfTime, RowNumber) AS BookingID FROM booking;

SELECT RowNumber, Email, CONCAT(PerfDate, PerfTime, RowNumber) AS BookingID FROM booking;

SELECT RowNumber, Email, CONCAT((CONCAT(PerfDate, PerfTime, RowNumber) AS BookingID 
   FROM booking)BasicTicketPrice*BookingID);

SELECT RowNumber, Email, CONCAT(PerfDate, PerfTime, RowNumber) AS BookingID INTEGER 
FROM booking;

SELECT RowNumber FROM booking
LEFT JOIN (SELECT Title FROM performance WHERE '2017-11-01 19:00:00' Email IS NULL);

但它没有用。

有什么建议吗?我会感激任何想法。

1 个答案:

答案 0 :(得分:0)

假设:

  • 每预订座位预订一行
  • TitleProduction
  • 的合适主键
  • PerformanceDate, PerformanceTimePerformance
  • 的合适主要组合键

您将根据上面假设的键将三个表连接在一起。您似乎希望按预订门票的人将预订分组在一起 - 如果是这样,您需要使用汇总来显示座位号(我使用GROUP_CONCAT来划分它们),以及COUNT购买的门票,并乘以门票费用。

SELECT 
   b.Email, prod.Title, per.PerformanceDate, per.PerformanceTime, 
   GROUP_CONCAT(RowNumber) AS BookedSeats, 
   COUNT(RowNumber) * prod.BasicTicketPrice AS TotalCost
FROM Booking b
INNER JOIN Performance per  
     ON b.PerformanceDate = per.PerformanceDate 
        AND b.PerformanceTime = per.PerformanceTime
INNER JOIN Production prod
     ON per.Title = prod.Title
GROUP BY 
   b.Email, prod.Title, per.PerformanceDate, per.PerformanceTime, prod.BasicTicketPrice
ORDER BY prod.Title, per.PerformanceDate, per.PerformanceTime;

从技术上讲,我们应该在GROUP BY中包含所有非聚合列,因此也会列出prod.BasicTicketPrice