我想要实现的是一个查询,它在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'
答案 0 :(得分: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
答案 1 :(得分:1)
使用COALESCE()
功能。它返回其第一个非空的参数。
WHERE `Customer ID` = '1' and COALESCE(`Appointment Date`, `Backup Date`) ='2013-10-10' ;
答案 2 :(得分: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'))