如果子查询返回null,则Mysql返回null

时间:2014-03-20 15:11:53

标签: mysql subquery

Hy家伙,有时我的子查询返回null,这是好的,它应该返回null,但在那些情况下,我希望我的"父选择"返回null。

这可能吗?

如果是,那怎么样?

下面是代码:

SELECT 
    `company`.`companyID`,
    `company`.`companyName`, 
    `company`.`companyName`, 
    `company`.`companyEmail`, 
    `company`.`contactEmail`,
    `company`.`companyTel`,                 
    (
        SELECT 
            `package_map`.`szekhely_endDate`
        FROM 
            `package_map` 
        WHERE 
            `package_map`.`companyID` = `company`.`companyID`
        AND 
            `package_map`.`active` = 1
        AND 
            `package_map`.`szekhely_endDate` > NOW()
        ORDER BY 
            `package_map`.`szekhely_endDate` DESC 
        LIMIT 1
    ) as endDate,
CASE 
    WHEN endDate = NULL

FROM 
    `company` 
WHERE 
    `company`.`companyBase` = 'some address' 
AND 
    `company`.`szekhely_check_out` = 0

1 个答案:

答案 0 :(得分:2)

在两个表之间使用普通的INNER JOIN。如果package_map表中没有匹配的行,则结果中不会有一行。要获取最新的endDate,请使用MAX()函数。

SELECT 
    `company`.`companyID`,
    `company`.`companyName`, 
    `company`.`companyName`, 
    `company`.`companyEmail`, 
    `company`.`contactEmail`,
    `company`.`companyTel`,                 
    MAX(package_map.szekhely_endDate) AS endDate
FROM company
INNER JOIN package_map ON `package_map`.`companyID` = `company`.`companyID`
WHERE 
    `company`.`companyBase` = 'some address' 
AND 
    `company`.`szekhely_check_out` = 0
AND 
    `package_map`.`active` = 1
AND 
    `package_map`.`szekhely_endDate` > NOW()
GROUP BY `company`.`companyID`