0

Hy guys, sometimes my subquery return null which is ok, it should return null, but in those cases i would like my "parent select" to return null.

Is that possible?

And if yes, then how?

Heres the code:

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
  • JOIN with the subquery instead of putting it in the SELECT clause. Commented Mar 20, 2014 at 15:14

1 Answer 1

2

Use an ordinary INNER JOIN between the two tables. If there's no matching rows in the package_map table, there won't be a row in the result. To get the latest endDate, use the MAX() function.

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`
Sign up to request clarification or add additional context in comments.

3 Comments

i get Unknown column 'company.companyID' in 'where clause' error
Oh, I didn't notice that it was a correlated subquery. I need to rethink this.
Ok please let me know if you got something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.