如何根据具体情况从2表中获取数据

时间:2018-05-31 16:21:11

标签: php mysql

在MySQL数据库中,我有3个名为供应商车辆已分配表的表。

车辆表:

vid     vehicleName     noOfSeat     sid
========================================
13      x               10           28 
14      x               8            28
15      x               12           28
16      x               14           29 
17      x               4            29
18      x               8            30

已分配的表格

asgid   bid  sid  vid   did  seatBooked   assigned_start    assigned_end
============================================================================
56      15   28   13    17   3            06/01/2018 02:01  06/01/2018 04:02
57      15   28   14    15   2            06/01/2018 02:01  06/01/2018 04:02
58      15   28   15    16   3            06/01/2018 02:01  06/01/2018 04:02

在预订页面中,我需要将车辆分配到所选日期 06/01/2018 02:01 06/01 / 2018 04:02

现在,我想显示所选供应商的所有车辆以及vehicle表中的座位数

但条件是:

这些车辆将显示我所选日期的座位数: 6/01/2018 02:01 06/01 / 2018 04:02

例如:

必须在车辆上显示座位数后显示:

vid    Mp pf Seat available
===========================
13     7 ( why 7? because on my selected date 3 seats booked)
14     6 ( why 6? because on my selected date 2 seats booked)
15     9 ( why 9? because on my selected date 3 seats booked)
16     14
17     4
18     8

就像公交车票系统一样。

我当前的查询:

目前,我正在使用以下查询,但它只是删除了我所选日期的那个视频,但它不正确,因为您可以看到在我选择的日期,几个座位都可用!

// my selected date: From = '$timestart' and To = '$timeend'
foreach ($sid as $key => $value) {
    $vehicle->rowQuery("select * from vehicle where vid not in (
    select vid from assigned where assigned_start BETWEEN '$timestart' AND '$timeend' AND assigned_end BETWEEN '$timestart' AND '$timeend' ) AND sid = $value ");
}

我无法想象如何解决它:=(

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您可以这样做:

select vehicle.*, (noOfSeat -  
  (select sum(seatBooked)
    from assigned
    where sid = 28
    and (assigned_start between '2018-01-06 02:01' and '2018-01-06 04:02' )
    and (assigned_end between '2018-01-06 02:01' and '2018-01-06 04:02')
  )) as seatsAvailable
from vehicle
having seatsAvailable > 0

http://sqlfiddle.com/#!9/c6bcb6/15