如何在排除一条记录的同时查询重叠的约会?

时间:2019-02-18 22:04:13

标签: mysql

我正在尝试检查重叠的约会,但不包括当前记录,但似乎无法获得有效的查询。

     SELECT COUNT(1) as tCount 
     FROM appointment 
     EXCEPT appointment.appointmentId = 3
     WHERE appointment.`start` >= "2019-02-06 08:15:00.000" 
     AND appointment.`end`  <= "2019-02-06 08:30:00.000" 

当我删除“ except”行时,这工作得很好,并且我可以获得正确数量的记录。我只是不确定如何排除一条记录。

Database Schema

这是我遇到的错误。

[Warning, Error code 1,064, SQLState 42000] 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 'EXCEPT appointment.appointmentId = 3' at line 4

这是调用SQL的Java部分:

  String overlapCheck = "SELECT COUNT(1) as tCount \n" +
                        " FROM appointment \n" +
                        " WHERE appointment.`start` <= \"" + start +       
                        "\" AND appointment.`end`  >= \"" + end + "\""
                    + " AND appointment.appointmentId <> \"" + check + "\"" ;     

                System.out.println(overlapCheck);

                ResultSet value = accessDB(overlapCheck);
                        int number = 0; 
                        if(value.next()){           
                           number = value.getInt(1) ;
                         }

                System.out.println("The number over overlapping appointments is " + number );

                if (number >= 1){ 
                    errorLabel.setText("Overlapping appointment times, please adjust.");

以及数据库数据的图片:

Database data

当我检查重叠时,查询似乎正常工作。我打算让它们完全不重叠。

1 个答案:

答案 0 :(得分:1)

没有提供示例数据,我们可以确保其余的查询都是正确的,但是可以肯定的是,EXCEPT在MySQL中不是有效的关键字。在使用Microsoft SQL Server时,您可能会遇到它,但这并不是所有SQL实现中的标准。

在这种情况下,您可以在WHERE中用一个额外的子句很简单地替换它:

SELECT COUNT(1) as tCount 
FROM appointment 
WHERE appointment.`start` >= "2019-02-06 08:15:00.000" 
AND appointment.`end`  <= "2019-02-06 08:30:00.000" 
AND appointment.appointmentId <> 3

这将解决您的语法错误。假设其余逻辑满足您的要求,那么您的查询现在应该可以正常工作了。