如何在MySql中测试时间相等性

时间:2014-04-16 22:06:28

标签: mysql sql database

我有下一个查询:

UPDATE flights, airlines 
SET flights.business_booked_seats = flights.business_booked_seats + 3 
WHERE flights.airline_id = airlines.id 
AND airlines.name = EasyJet 
AND flights.origin_airport = London 
AND flights.destination_airport = Tokyo 
AND flights.departingDate = 2014-04-16 
AND flights.arrival_date = 2014-04-17 
AND flights.departing_time = 11:30:00 
AND flights.arrival_time = 04:00:00

我得到了

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':30:00 AND flights.arrival_time = 04:00:00' at line 1

我也试过TIME(11:30:00),但它没有用。

表的结构如下:

Airlines[id(int), name(varchar)]

Flights[origin_airport(varchar), destination_airport(varchar), departing_date(date), arrival_date(date), departing_time(time), arrival_time(time), economy_capacity(int), business_capacity(int), economy_booked_seats(int), business_booked_seats(int), economy_price(decimal), business_price(decimal), airline_id(int)]

如何正确编写查询?

2 个答案:

答案 0 :(得分:3)

正如评论中所建议的,使用datetime类型可能更有意义。除此之外,您希望将时间文字用单引号括起来。 '11:30:00'

TIME()不会这样做 - 它需要表达式作为参数,而11:30:00不是,但是TIME '11:30:00'会冗余地完成相同的操作只需将它留在单引号中即可。

https://dev.mysql.com/doc/refman/5.6/en/date-and-time-literals.html

由于我不能因声誉而发表评论,我在此处补充说,使用STR_TO_DATE是不必要的。

答案 1 :(得分:2)

您需要尊重SQL格式。

所有字符串都在引号之间(双引号或单引号),因此您需要:

AND airlines.name = 'EasyJet'
AND flights.origin_airport = 'London'
AND flights.destination_airport = 'Tokyo'

您可以使用STR_TO_DATE function

将字符串转换为日期和时间
AND flights.departingDate = STR_TO_DATE('2014-04-16','%Y-%m-%d')
AND flights.arrival_date = STR_TO_DATE('2014-04-17','%Y-%m-%d')

或者您可以比较字符串:

AND flights.departingDate = '2014-04-16'
AND flights.arrival_date '2014-04-17'
AND flights.departing_time = '11:30:00'
AND flights.arrival_time = '04:00:00'

附录:STR_TO_DATE如果您使用的是非YYYY-MM-DD的其他格式,则对您有用。它在没有STR_TO_DATE的情况下工作,因为你足够好以提供该格式的日期,但其他格式(如通常的英语MM/DD/YYYY将不会自动匹配)。