mysql>
SELECT producer_name FROM producer WHERE producer_name -> IN (SELECT engineer_name FROM engineer);+---------------+
| producer_name |
+---------------+
| George Martin |
+---------------+
1 row inset sec)
Let’s rewrite the query to use EXISTS. First, think about the subquery: it should produce output when there’s an engineer with the same name as a producer.
Second, think about the outer query it should return the producer’s name when the inner query produces output. Here’s the rewritten query:
mysql>
SELECT producer_name FROM producer WHERE EXISTS -> (SELECT * FROM engineer WHERE producer_name = engineer_name);
+---------------+
| producer_name |
+---------------+
| George Martin |
+---------------+
1 row inset sec)
Again, you can see that the subquery references the producer_name column, which comes from the outer query.
Correlated subqueries can be used with any nested query type. Here’s
the previousIN
query rewritten with an outer reference:
mysql>
SELECT producer_name FROM producer WHERE producer_nameShare with your friends: