简体   繁体   中英

how to handle If a subquery (inner query) returns a null value to the outer query

I have a vertical table like this:

id Profile_id feature_id value
1 1 1 Rick
2 1 2 Novak
3 5 3 5428
4 5 1 Joe
... ... ... ...

(above table is short part of profile_features table)

I have a query:

SELECT * FROM(SELECT `value` TelNum FROM `profile_features` WHERE `feature_id` IN (10, 64, 103) AND `profile_id` = 16752 LIMIT 1) as TelNum,
    (SELECT `value` NCode From `profile_features` WHERE `feature_id` IN (5, 61, 100) AND `profile_id` = 16752 LIMIT 1)  AS NCode,
    (SELECT `value` Fname From `profile_features` WHERE `feature_id` IN (1, 55, 86) AND `profile_id` = 16752 LIMIT 1) AS Fname,
    (SELECT `value` Lname From `profile_features` WHERE `feature_id` IN (2, 56, 95) AND `profile_id` = 16752 LIMIT 1) AS Lname

but if one of the subqueries returns null, query have not any output.

I want a row result with TelNum, NCode, Fname, Lname either they are Null or not null.

You could use scalar subqueries in the select-list instead of your current Cartesian product:

SELECT (SELECT `value` FROM `profile_features` WHERE `feature_id` IN (10, 64, 103) AND `profile_id` = 16752 LIMIT 1) as TelNum,
  (SELECT `value` From `profile_features` WHERE `feature_id` IN (5, 61, 100) AND `profile_id` = 16752 LIMIT 1)  AS NCode,
  (SELECT `value` From `profile_features` WHERE `feature_id` IN (1, 55, 86) AND `profile_id` = 16752 LIMIT 1) AS Fname,
  (SELECT `value` From `profile_features` WHERE `feature_id` IN (2, 56, 95) AND `profile_id` = 16752 LIMIT 1) AS Lname;

Alternatively, you could learn to use LEFT OUTER JOIN:

SELECT TelNum.TelNum, NCode.NCode, Fname.Fname, Lname.Lname
FROM (SELECT NULL AS dummy) AS dummy
LEFT OUTER JOIN (SELECT `value` TelNum FROM `profile_features` WHERE `feature_id` IN (10, 64, 103) AND `profile_id` = 16752 LIMIT 1) AS TelNum ON true
LEFT OUTER JOIN (SELECT `value` NCode From `profile_features` WHERE `feature_id` IN (5, 61, 100) AND `profile_id` = 16752 LIMIT 1) AS NCode ON true
LEFT OUTER JOIN (SELECT `value` Fname From `profile_features` WHERE `feature_id` IN (1, 55, 86) AND `profile_id` = 16752 LIMIT 1) AS Fname ON true
LEFT OUTER JOIN (SELECT `value` Lname From `profile_features` WHERE `feature_id` IN (2, 56, 95) AND `profile_id` = 16752 LIMIT 1) AS Lname ON true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM