Learning Mysql


-> SELECT artist_id, album_id, track_id, 1 FROM track LIMIT 1



Download 4.24 Mb.
View original pdf
Page256/366
Date04.08.2023
Size4.24 Mb.
#61806
1   ...   252   253   254   255   256   257   258   259   ...   366
Learning MySQL
-> SELECT artist_id, album_id, track_id, 1 FROM track LIMIT 1;
ERROR 1062 (23000): Duplicate entry '1' for key If you want MySQL to ignore this and keep going, add an
IGNORE
keyword after the
INSERT
:
mysql> INSERT IGNORE INTO shuffle (artist_id, album_id, track_id, sequence_id)
-> SELECT artist_id, album_id, track_id, 1 FROM track LIMIT 1;
280 | Chapter 8:
Doing More with MySQL

Query OK, 0 rows affected (0.00 sec)
Records: 1 Duplicates 1 Warnings 0
MySQL doesn’t complain, but it does report that it encountered a duplicate. Prior to
MySQL 4.0.1, the
IGNORE
mode was the default behavior, but for later versions, you have to add the keyword if you want duplicates to be ignored.
Finally, note that for versions of MySQL older than 4.0.14, you couldn’t insert into a table that’s listed in the
SELECT
statement, since the
SELECT
would find the newly inserted rows and try to insert them again. On newer systems, you still need to avoid duplicate primary keys:
mysql> INSERT INTO artist SELECT artist_id,artist_name FROM artist;
ERROR 1062 (23000): Duplicate entry '1' for key but you can modify values in the
SELECT
statement to get a different primary key value and insert it back into the same table:
mysql> INSERT INTO artist SELECT 10*artist_id,artist_name FROM artist;
Query OK, 6 rows affected (0.00 sec)
Records: 6 Duplicates 0 Warnings Here, we’re copying the rows but multiplying their artist_id s by 10 before we insert them. This is the result:
mysql> SELECT * FROM artist;
+-----------+---------------------------+
| artist_id | artist_name |
+-----------+---------------------------+
| 1 | New Order |
| 2 | Nick Cave & The Bad Seeds |
| 3 | Miles Davis |
| 4 | The Rolling Stones |
| 5 | The Stone Roses |
| 6 | Kylie Minogue |
| 60 | Kylie Minogue |
| 50 | The Stone Roses |
| 40 | The Rolling Stones |
| 30 | Miles Davis |
| 20 | Nick Cave & The Bad Seeds |
| 10 | New Order |
+-----------+---------------------------+
12 rows inset sec)

Download 4.24 Mb.

Share with your friends:
1   ...   252   253   254   255   256   257   258   259   ...   366




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

    Main page