Learning Mysql


-> UNION -> (SELECT artist_name FROM artist WHERE artist_id > 7)



Download 4.24 Mb.
View original pdf
Page223/366
Date04.08.2023
Size4.24 Mb.
#61806
1   ...   219   220   221   222   223   224   225   226   ...   366
Learning MySQL
-> UNION
-> (SELECT artist_name FROM artist WHERE artist_id > 7)
-> ORDER BY artist_name LIMIT 4;
+---------------------------+
| artist_name |
+---------------------------+
| Miles Davis |
| New Order |
| Nick Cave & The Bad Seeds |
| The Rolling Stones |
Advanced Joins | 245


+---------------------------+
4 rows inset sec)
The
UNION
operation is somewhat unwieldy, and there are generally alternative ways of getting the same result. For example, the previous query could have been written more simply as:
mysql> SELECT artist_name FROM artist WHERE
-> artist_id < 3 OR artist_id > 5
-> ORDER BY artist_name LIMIT 4;
+---------------------------+
| artist_name |
+---------------------------+
| Kylie Minogue |
| New Order |
| Nick Cave & The Bad Seeds |
+---------------------------+
3 rows inset sec)
The Left and Right Joins
The joins we’ve discussed so far output only rows that match between tables. For example, when you join the track and played tables, you see only the tracks that have been played. Therefore, rows for tracks that haven’t been played are ignored and—if they existed—would play data for tracks that don’t exist. This makes sense in many cases, but it isn’t the only way to join data. This section explains other options you have.
Suppose you did want a comprehensive list of all albums and the number of times you’ve played tracks from them. Unlike the example earlier in this chapter, included in the list you want to see a zero next to albums that haven’t been played. You can do this with a left join, a different type of join that’s driven by one of the two tables participating in the join. A left join works like this each row in the left table—the one that’s doing the driving—is processed and output, with the matching data from the second table if it exists and
NULL
values if there is no matching data in the second table.
We’ll show you how to write this type of query later in this section, but we’ll start with a simpler example.
Here’s a simple LEFT JOIN
example. You want to list all tracks, and next to each track you want to show when it was played. If a track has been never been played, you want to see that. If it’s been played many times, you want to see that too. Here’s the query:
mysql> SELECT track_name, played FROM

Download 4.24 Mb.

Share with your friends:
1   ...   219   220   221   222   223   224   225   226   ...   366




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

    Main page