Learning Mysql


-> artist_name = "New Order" AND



Download 4.24 Mb.
View original pdf
Page266/366
Date04.08.2023
Size4.24 Mb.
#61806
1   ...   262   263   264   265   266   267   268   269   ...   366
Learning MySQL
-> artist_name = "New Order" AND
-> artist.artist_id = album.artist_id AND
-> artist.artist_id = track.artist_id AND
-> album.album_id = track.album_id;
Query OK, 93 rows affected (0.10 sec)
The query identifies the artist_id of "New Order"
and performs a join between the tables.
We prefer the newer syntax because it is clearer DELETE FROM
some tables
USING
other tables to drive the querying process.
Note that you can use clauses such as LEFT JOIN
and INNER JOIN
in
DELETE
statements.
However, you can’t delete from a table that’s read from in a nested subquery, such as in the following line:
mysql> DELETE FROM artist WHERE artist_id IN (SELECT artist_id FROM artist);
ERROR 1093 (HY000): You can't specify target table 'artist' for update in
FROM clause
In multiple table deletes, you can’t use ORDER BY
or
LIMIT
clauses.
290 | Chapter 8:
Doing More with MySQL


Updates
Now we’ll contrive an example using the music database to illustrate multiple-table updates. We’ve decided to highlight albums we’ve played. Our method of highlighting is to change the album’s name to all capital letters. To begin, let’s display albums we’ve played:
mysql> SELECT DISTINCT album_name FROM
-> album INNER JOIN track USING (artist_id, album_id)
-> INNER JOIN played USING (artist_id, album_id, track_id);
+----------------------------+
| album_name |
+----------------------------+
| Retro - Miranda Sawyer POP |
| Live Around The World |
+----------------------------+
2 rows inset sec)
Now, let’s put that query into an
UPDATE
statement:
mysql> UPDATE album INNER JOIN track USING (artist_id, album_id)
-> INNER JOIN played USING (artist_id, album_id, track_id)
-> SET album_name = UPPER(album_name);
Query OK, 2 rows affected (0.01 sec)
Rows matched 11 Changed 2 Warnings Lets look at the syntax a multiple-table update looks similar to a
SELECT
query. The
UPDATE
statement is followed by a list of tables that incorporates whatever join clauses you need or prefer in this example, we’ve used INNER JOIN
to bring together the artist
,
album
, and track tables. This is followed by the keyword SET, with assignments to individual columns in this example, you can see that only one column is modified (to put the album name in uppercase, so columns in all other tables besides album aren’t modified. An optional
WHERE
may in turn follow (but doesn’t in this example, since the
USING
clause does it for us).
To illustrate using a
WHERE
clause, here’s the previous query rewritten with the join expressed using
WHERE
:
mysql> UPDATE artist, album, track, played

Download 4.24 Mb.

Share with your friends:
1   ...   262   263   264   265   266   267   268   269   ...   366




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

    Main page