I have two tables:
+---------+-----------------+----------+----------+----------+---------+
| TrackId | URI | ArtistID | Title | AlbumID | BitRate |
+---------+-----------------+----------+----------+----------+---------+
| 1 | /home/music/... | 234 | atune | 8958223 | 192 |
| 2 | /music/uri1/... | 427 | goodsong | 222 | 192 |
| 3 | /music/uri2/... | 427 | goodsong | 222 | 128 |
| 4 | /music/uri3/... | 427 | goodsong | 222 | 160 |
| 5 | /home/music/... | 427 | goodsong | 333 | 128 |
| 6 | /home/music/... | 522 | another | 3458859 | 128 |
+---------+-----------------+----------+----------+----------+---------+
and
+----------+------------+
| AlbumID | AlbumTitle |
+----------+------------+
| 8958223 | titleA |
| 222 | titleB |
| 333 | titleC |
| 3458859 | titleD |
+----------+------------+
Simply put, what I want is this:
+---------+-----------------+----------+----------+----------+------------+---------+
| TrackId | URI | ArtistID | Title | AlbumId | AlbumTitle | BitRate |
+---------+-----------------+----------+----------+----------+------------+---------+
| 3 | /music/uri2/... | 427 | goodsong | 222 | titleB | 128 |
| 4 | /music/uri3/... | 427 | goodsong | 222 | titleB | 160 |
+---------+-----------------+----------+----------+----------+------------+---------+
This is an attempt to remove duplicates that have the:
- same title
- same artist id
- different track id
- the non-highest bitrate duplicates
- same album name from the album table
while not returning the entry with the highest bitrate duplicate
I’ve asked a very similar question here: Select duplicates from a single row?
The solution to that was:
SELECT c1.*
FROM CoreTracks c1
,(SELECT Title, ArtistID, MAX(FileSize) AS maxFileSize, MAX(BitRate) maxBitRate
FROM CoreTracks
GROUP BY Title, ArtistID) c2
WHERE c1.Title = c2.Title
AND c1.ArtistID = c2.ArtistID
AND (c1.FileSize != c2.maxFileSize AND c1.BitRate != c2.maxBitRate)
…but I cannot seem to wrap my head around dealing with another table this time around.
Give this a try:
Here is the SQL Fiddle.
–EDIT
To add the Album Title:
And the updated fiddle.
Good luck.