找不到任何内容时,为select语句定义返回参数

时间:2012-12-26 19:22:35

标签: mysql sql

这是我的选择声明。它做了什么?

  • 检查数据库中是否已有指定日期的约会
  • 检查用户是否在该特定时间工作。

使用mysql_num_rows($result)我检查是否有任何行。如果它返回0,则可以添加约会,如果它返回其他内容(数据库中已经有约会),则会被阻止。

该声明适用于第1点。如果已经有约会,则返回1或更多。但是当所选日期超出用户的工作小时范围时,它也会返回0.

问题:当用户在特定时间

时,我可以添加哪些内容以获取返回的行(mysql_num_rows返回1或更多)? >

工作小时范围示例:08:00:00 to 17:00:00

select * 
from ios_appointments a join ios_workinghours h using(workerid_fk) 
where workerid_fk = 1 
AND h.start <= '19:57:20' AND h.end >= '20:57:20' 
AND ( 
   a.start BETWEEN '2012-12-24 19:57:20'  AND  '2012-12-24 20:57:20' 
   OR  a.end   BETWEEN '2012-12-24 19:57:20'  AND  '2012-12-24 20:57:20' 
   OR (a.start < '2012-12-24 19:57:20' AND a.end > '2012-12-24 20:57:20') 
)

1 个答案:

答案 0 :(得分:0)

您可以返回一行空值:

select * 
from ios_appointments a join ios_workinghours h using(workerid_fk) 
where workerid_fk = 1 
AND h.start <= '19:57:20' AND h.end >= '20:57:20' 
AND ( 
   a.start BETWEEN '2012-12-24 19:57:20'  AND  '2012-12-24 20:57:20' 
   OR  a.end   BETWEEN '2012-12-24 19:57:20'  AND  '2012-12-24 20:57:20' 
   OR (a.start < '2012-12-24 19:57:20' AND a.end > '2012-12-24 20:57:20') 
)
union
select null, null, null -- how every many column are in the first part
where not exists (
    select * 
    from ios_appointments a join ios_workinghours h using(workerid_fk) 
    where workerid_fk = 1 
    AND h.start <= '19:57:20' AND h.end >= '20:57:20' 
    AND ( 
       a.start BETWEEN '2012-12-24 19:57:20'  AND  '2012-12-24 20:57:20' 
       OR  a.end   BETWEEN '2012-12-24 19:57:20'  AND  '2012-12-24 20:57:20' 
       OR (a.start < '2012-12-24 19:57:20' AND a.end > '2012-12-24 20:57:20') 
    )
)

如果您的查询什么都没找到,则返回一行空值,如果找到行,则返回现在的行。

您可以返回所需的任何值,而不是空值。