I have an application in Java requiring me to find specific records given specific conditionals. For example, I have the table:
| id | song | artist | record_label |
|---|---|---|---|
| 1 | Never Gonna Give You Up | Rick Astley | Rickroll'd Records |
| 2 | Blackbird | The Beatles | Apple Records |
| 3 | Yesterday | The Beatles | Apple Records |
| 4 | WonderWall | Oasis | Columbia Records |
I'd like to bulk query a subset of them based on specific conditions. Something similar to:
SELECT id FROM songs
WHERE
(song = 'Blackbird' AND artist = 'The Beatles' AND record_label = 'Apple Records') OR
(song = 'WonderWall' AND artist = 'Oasis' AND record_label = 'Columbia Records') OR
(song = 'Yesterday' AND artist = 'The Beatles' AND record_label = 'Apple Records')
The application is going to receive these conditions from the user and could be trying to find thousands of these records. As a result, I'm hoping to find a way to do this without any case of SQL injection and in as little queries as possible.
MY first approach would be some flavor of PreparedStatement where I iterate through this SQL query to query each individual record:
SELECT id from songs WHERE song = ? AND artist = ? AND record_label = ?
This prevents SQL injection, but I feel like this could be optimized more as we hammer the DB with thousands of these requests in seconds.
Another option is to create a temp table, import our passed conditions into the temp table and do an INNER JOIN on the songs table to only retrieve the rows that match between the 2. This solves both problems, but it requires a good amount of development work.
I'm wondering if there's any other methods I haven't taken into account. Thanks in advance for any suggestions!