0

嗨,我想要实现的是一个查询,它在 where 子句中有一个动态列名,具体取决于列是否为空。

例如,如果一行的约会日期不为空,则 where 子句将是:

WHERE `Building ID` = '1' and `Appointment Date`='2013-10-10' ;

如果约会日期为空,则 where 子句将是:

WHERE `Building ID` = '1' and `Backup Date`='2013-10-10' ;  

现在我在 where 子句中的子查询返回太多行,所以查询失败,我应该如何解决这个问题?

我的查询如下:

SELECT `Job ID` 
FROM jobs 
WHERE `Building ID` = '1' 
and (select case when `Appointment Date` IS NOT NULL THEN `Appointment Date` 
else `Backup Date` end FROM jobs WHERE `Building ID` = '1') = '2013-10-10'  
4

3 回答 3

1
SELECT `Job ID` 
FROM jobs 
WHERE `Building ID` = '1' 
and case when `Appointment Date` IS NOT NULL 
         then `Appointment Date` = '2013-10-10' 
         else `Backup Date` = '2013-10-10'
    end
于 2013-07-20T23:07:17.190 回答
1

使用该COALESCE()功能。它返回其第一个不为空的参数。

WHERE `Customer ID` = '1' and COALESCE(`Appointment Date`, `Backup Date`) ='2013-10-10' ;
于 2013-07-20T23:07:40.757 回答
0

试试这个:

SELECT `Job ID` 
FROM jobs 
WHERE `Building ID` = '1' 
AND ((`Appointment Date` IS NOT NULL AND `Appointment Date` = '2013-10-10') 
      OR
     (`Appointment Date` IS NULL AND `Backup Date` = '2013-10-10'))
于 2013-07-20T23:07:46.133 回答