Learning Mysql


-> (SELECT * FROM album WHERE album_name = artist_name)



Download 4.24 Mb.
View original pdf
Page237/366
Date04.08.2023
Size4.24 Mb.
#61806
1   ...   233   234   235   236   237   238   239   240   ...   366
Learning MySQL
-> (SELECT * FROM album WHERE album_name = artist_name);
+-------------+
| artist_name |
+-------------+
| The Beatles |
+-------------+
1 row inset sec)
So, the query works now, we just need to understand how!
Let’s examine the subquery in our previous example. You can see that it lists only the album table in the
FROM
clause, but it uses a column from the artist table in the
WHERE
clause. If you run it in isolation, you’ll see this isn’t allowed:
mysql> SELECT * FROM album WHERE album_name = artist_name;
ERROR 1054 (S Unknown column 'artist_name' in 'where clause'
Nested Queries | 259

However, it’s legal when executed as a subquery because tables listed in the outer query are allowed to be accessed in the subquery. So, in this example, the current value of artist_name in the outer query is supplied to the subquery as a constant, scalar value and compared to the album name. If the album name matches the artist name, the subquery is true, and so the outer query outputs a row. Consider two cases that illustrate this more clearly When the artist_name being processed by the outer query is New Order, the sub- query is false because SELECT * FROM album WHERE album_name = "New Order"
doesn’t return any rows, and so the artist row for New Order isn’t output as an answer When the artist_name being processed by the outer query is The Beatles, the sub- query is true because SELECT * FROM album WHERE album_name = "The Beatles"
returns at least one row. Overall, the artist row for The Beatles is output as an answer.
Can you seethe power of correlated subqueries? You can use values from the outer query in the inner query to evaluate complex information needs.
We’ll now explore another example using EXISTS. Let’s try to find all artists from whom we own at least two albums. To do this with EXISTS, we need to think through what the inner and outer queries should do. The inner query should produce a result only when the condition we’re checking is true in this case, it should produce output when the artist has at least two albums in the database. The outer query should produce the artist name whenever the inner query is true. Here’s the query:
mysql> SELECT artist_name FROM artist WHERE EXISTS

Download 4.24 Mb.

Share with your friends:
1   ...   233   234   235   236   237   238   239   240   ...   366




The database is protected by copyright ©ininet.org 2024
send message

    Main page