简体   繁体   中英

MySQL: How do I return all unique values from one column while matching values in another column

I have a MySQL DB storing song metadata. Two of the existing columns in Table Music are Rating and Title. The DB is over 9 GB large. I would like to find all unique song titles where the rating is below a value on a 0-10 scale, say 3. (Unique here meaning I only need to see a song title once.)

Once I get the resulting list of song titles, I will delete those low-rated songs form the DB. However, I have another table in the DB called Albums and I never want to delete any songs in any Album listed there.

What I have tried so far is:

SELECT DISTINCT Title FROM Music WHERE
Title NOT IN (SELECT Title FROM Music WHERE Rating >= 3)
AND Song NOT IN (SELECT Song FROM Albums)
ORDER BY Title desc

This query might work; I don't know because it has been running for hours. So I also need help in finding a faster way to get the results.

Get songs from MUSIC with rating below 3 then do a left join with ALBUM on key: song. But also put a filter where song in MUSIC is not found in album.

 SELECT DISTINCT T.TITLE
FROM MUSIC T
LEFT JOIN ALBUM A ON T.SONG = A.SONG
WHERE T.RATING < 3 
       AND A.SONG IS NULL
ORDER BY T.TITLE DESC;

see demo here;
http://sqlfiddle.com/#!9/65c2455/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM