3

请考虑以下两个表格:

Holidays
HolidayID (PK)
Destination
Length
MaximumNumber
...


Bookings
BookingID  (PK)
HolidayID (FK)
Name
...

客户可以预订假期(例如去夏威夷)。但是,假设给定的假期有最大数量的地方。例如,今年夏威夷只有 75 个假期(忽略其他年份)。

因此,如果某些客户想预订去夏威夷度假。我需要计算 Bookings 表中的记录,如果该数字大于 75,我必须告诉客户为时已晚。我可以使用 2 个 MySQL 查询(1 个获取假期的 MaximumNumber,2 个从 Bookings 获取当前总数)和 PHP(例如)将计数值与夏威夷假期的最大数量进行比较。但我想知道是否有办法纯粹在 SQL 中做到这一点(在这种情况下是 MySQL)?即计算夏威夷的预订数量并与夏威夷的 MaximumNumber 值进行比较。

编辑:我的方法:

$query1 = "SELECT MaximumNumber FROM Holidays WHERE HolidayID=$hawaiiID";

$query2 = "SELECT COUNT(BookingID) FROM Bookings WHERE HolidayID=$hawaiiID";

因此,如果第一个查询给出 75,第二个查询给出 75,我可以在 PHP 中比较这些值。但我想知道是否有办法仅在 SQL 中以某种方式做到这一点。

4

3 回答 3

0

Maybe I am missing something, but why not use a subquery to determine the total bookings for each holidayid:

select *
from holidays h
left join
(
  select count(*) TotalBooked, HolidayId
  from bookings
  group by holidayId
) b
  on h.holidayId = b.holidayId
WHERE h.HolidayID=$hawaiiID;

See SQL Fiddle with Demo.

Then you could use a CASE expression to compare the TotalBooked to the MaxNumber similar to this:

select h.destination,
  case 
    when b.totalbooked = h.maxNumber
    then 'Not Available'
    else 'You can still book' end Availability
from holidays h
left join
(
  select count(*) TotalBooked, HolidayId
  from bookings
  group by holidayId
) b
  on h.holidayId = b.holidayId
WHERE h.HolidayID=$hawaiiID;

See SQL Fiddle with Demo.

You will notice that I used a LEFT JOIN which will return all rows from the Holidays table even if there are not matching rows in the Bookings table.

于 2013-02-10T15:33:32.327 回答
0

Something like this will work. You can fill in the details:

select case 
when 
(select count(*) 
from Bookings 
where holidayID = $hawaiiid) 
<= MaximumNumber then 'available' else 'sold out' end status
from holidays 
etc
于 2013-02-10T15:33:39.927 回答
0

你可以尝试这样的事情:

select case when b.freq < h.MaximumNumber
            then 'Available'
            else 'Not Available'
            end as MyResult
from Holidays h
left join (
   select HolidayID
        , count(*) as freq
   from Bookings
   where HolidayID=$hawaiiID
   group by HolidayID
   ) b
on h.HolidayID=b.HolidayID
于 2013-02-10T15:36:44.583 回答