MySQL:从结果中排除一些行?

时间:2018-05-05 07:07:59

标签: mysql sql

考虑下面的顾问不兼容表

c_id | start_date           |end_date
---------------------------------------------
937  | 2018-06-01 13:00:00  | 2018-06-01 20:00:00
937  | 2018-04-28 08:00:00  | 2018-04-28 18:00:00
938  | 2018-06-28 14:00:00  | 2018-06-28 16:00:00
938  | 2018-06-16 14:00:00  | 2018-06-16 17:00:00
939  | 2018-05-05 09:00:00  | 2018-05-05 12:00:00
939  | 2018-06-08 12:00:00  | 2018-06-08 16:00:00

现在我想在6月16日09:00到18:00之间获得顾问 这就是我到目前为止所做的:

SELECT c_id, start_date, end_date 
FROM consultant_unavailabilities 
WHERE start_date NOT BETWEEN '2018-06-16 09:00:00' AND '2018-06-16 18:00:00' 
AND end_date NOT BETWEEN '2018-06-16 09:00:00' AND '2018-06-16 18:00:00' 
GROUP BY c_id

返回:

937  | 2018-06-01 13:00:00  | 2018-06-01 20:00:00
938  | 2018-06-28 14:00:00  | 2018-06-28 16:00:00
939  | 2018-05-05 09:00:00  | 2018-05-05 12:00:00 

937和939都可以,但938不可用。

诀窍是要求MySQL在06年6月16日从09:00到18:00不要获得有一行不可用的ID。

我怎样才能实现这一目标?

4 个答案:

答案 0 :(得分:0)

您需要使用子查询来查找在此期间忙碌的所有顾问,然后将其排除在外:

SELECT c_id, start_date, end_date
FROM consultant_availabilities
WHERE c_id NOT IN (
    SELECT c_id
    FROM consultant_unavailabilities 
    WHERE start_date BETWEEN '2018-06-16 09:00:00' AND '2018-06-16 18:00:00' 
    OR end_date BETWEEN '2018-06-16 09:00:00' AND '2018-06-16 18:00:00')

答案 1 :(得分:0)

SELECT c_id, start_date, end_date 
FROM c_u 
WHERE (start_date < '2018-06-16 09:00:00' AND end_date < '2018-06-16 09:00:00') 
OR
(start_date > '2018-06-16 18:00:00' AND end_date > '2018-06-16 18:00:00')
AND 
c_id NOT IN (SELECT c_id FROM c_u WHERE 
             (start_date BETWEEN '2018-06-16 09:00:00' AND '2018-06-16 18:00:00')
             OR
             (end_date BETWEEN '2018-06-16 09:00:00' AND '2018-06-16 18:00:00')
            )
            GROUP BY c_id;

SQL Fiddle example

答案 2 :(得分:0)

year =  int(input('Enter year: '))
while year: # this line forces the program to continue until the user enters no data
   if year < 1962:
      print('Car did not exist yet!')
      print('Please enter a valid year after 1962')
   elif year <= 1964:
      print('$18500')
   elif year >= 1965 <= 1968:
      print('$6000')
   elif year >= 1969 <= 1971:
      print('$12000')
   else:
      print('Error Message') # You can change the error message to display if the year entered is after 1971
   year = int(input('Please enter another year: '))

答案 3 :(得分:0)

使用GROUP BYHAVING过滤您希望保留的顾问的ID:

SELECT c_id
FROM consultant_unavailabilities
GROUP BY c_id
HANING COUNT(*) = SUM(
    case when start_date BETWEEN '2018-06-16 09:00:00' AND '2018-06-16 18:00:00' 
        AND end_date between '2018-06-16 09:00:00' AND '2018-06-16 18:00:00'
        then 0 else 1 end
    )

Demo.

上面,COUNT为您提供了顾问的不可用记录总数,而SUM给出了不包括特定时间的不可用记录的数量。当这两个计数相等时,顾问可在您选择的期间内使用。