简体   繁体   中英

Using UNION sub query inside of NOT IN MySQL

I want to use a union sub query inside not null in MySQL. The query is shown below.

SELECT s.student_id
     , s.student_name
  FROM students` s
 WHERE s.student_id NOT IN (
    SELECT student_id
      FROM free_students
     UNION
    SELECT student_id
    FROM paid_students
)

If the UNION sub query returns null the query results also becomes null. How to handle these kind of situations?

I would use an exists clause, two of them actually:

SELECT s.student_id, s.student_name
FROM students s
WHERE NOT EXISTS (SELECT 1 FROM free_students fs WHERE s.student_id = fs.student_id) AND
      NOT EXISTS (SELECT 1 FROM paid_students ps WHERE s.student_id = ps.student_id);

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