如何使用主查询和子查询来使用BETWEEN条件

时间:2018-03-22 16:42:47

标签: mysql sql

我在3个表中使用JOIN并且计数和mysql查询工作正常,现在我的问题是我想在我的主查询中添加一个BETWEEN条件,这里{{3}你可以检查我的表模式。在trip_details表中,我使用此列只有一列名为tripDate,我必须在主查询中使用BETWEEN条件

Mysql查询:

    SELECT COUNT(T.tripId) as Escort_Count,
  (
      SELECT COUNT(*) FROM 
      (
          SELECT a.allocationId
          FROM trip_details a 
          INNER JOIN cab_allocation c ON a.allocationId = c.allocationId 
          WHERE c.`allocationType` =  'Adhoc Trip'
          GROUP BY a.allocationId
      ) AS Ad

  ) AS Adhoc_Trip_Count,
  (SELECT COUNT(id) FROM trip_details) as Total_Count
  FROM 
  ( 
      SELECT a.tripId FROM 
      trip_details a 
      INNER JOIN 
      escort_allocation b 
      ON a.allocationId = b.allocationId 
      GROUP BY a.allocationId 
  ) AS T 

1 个答案:

答案 0 :(得分:0)

您必须在以下每个子查询中添加WHERE子句:

  SELECT COUNT(T.tripId) as Escort_Count,
  (
      SELECT COUNT(*) FROM 
      (
          SELECT a.allocationId
          FROM escort_allocation a 
          INNER JOIN trip_details b ON a.allocationId = b.allocationId 
          INNER JOIN cab_allocation c ON a.allocationId = c.allocationId 
          WHERE c.allocationType = 'Adhoc Trip' AND tripDate BETWEEN '20180315' AND '20180320'
          GROUP BY a.allocationId
      ) AS Ad

  ) AS Adhoc_Trip_Count,
  (SELECT COUNT(id) FROM trip_details WHERE tripDate BETWEEN '20180315' AND '20180320') as Total_Count
  FROM 
  ( 
      SELECT a.tripId FROM 
      trip_details a 
      INNER JOIN 
      escort_allocation b 
      ON a.allocationId = b.allocationId 
      WHERE tripDate BETWEEN '20180315' AND '20180320'
      GROUP BY a.allocationId 
  ) AS T