Use subquery in mysql

时间:2016-10-20 19:05:18

标签: mysql

The query below gives me 2 out of the 3 answers I'm looking for. On the sub-query select I get null instead of no

the 3 possible values for column name isCyl could be blank, yes, no

I'm not sure if the sub-query is the best way to go about it, but I don't know how else to re-state the query.

The schedule table has a series of columns to show what tasks must be completed on an assignment. Related tables store the results of the tasks if they were assigned to be completed. So I need to test if a specific task was scheduled. If so, then I need to see if the results of the task have been recorded in the related table. For brevity I am only showing one of the columns here.

SELECT s.`reckey`,  
if(s.cylinders="T",
        (select 
            if(c.areckey is not null, 
                  "yes",
                  "no"
            ) 
            from cylinders c where c.areckey = s.reckey limit 1 
        )
        ,""
) as isCyl 
from schedule s 
where s.assignmentDate between 20161015 and 20161016 
order by s.reckey

1 个答案:

答案 0 :(得分:1)

Use a LEFT JOIN, which returns NULL for columns in the child table when there's no match.

SELECT s.reckey, IF(s.cylinders = "T",
                    IF(c.areckey IS NOT NULL, 'yes', 'no'),
                    "") AS isCyl
FROM schedule AS s
LEFT JOIN cylinders AS c ON c.areckey = s.reckey
WHERE s.assignmentDate between 20161015 and 20161016 
ORDER BY s.reckey

If there can be multiple rows in cylinders with the same areckey, change it to:

LEFT JOIN (select distinct areckey FROM cylinders) AS c on c.areckey = s.reckey

or use SELECT DISTINCT in the main query.