I have three simple tables as shown below:
+----+-------------+ +----+-----------+ +----+---------------+
| artists | | albums | | songs |
+----+-------------+ +----+-----------+ +----+---------------+
| id | name | | id | name | | id | name |
+----+-------------+ +----+-----------+ +----+---------------+
| 0 | The Beatles | | 0 | Help! | | 0 | Help! |
| 1 | Metallica | | 1 | Metallica | | 1 | Enter Sandman |
+----+-------------+ +----+-----------+ +----+---------------+
And I would like a query to result in the following:
+--------+---------------+
| type | name |
+--------+---------------+
| artist | The Beatles |
| artist | Metallica |
| album | Help! |
| album | Metallica |
| song | Help! |
| song | Enter Sandman |
+--------+---------------+
I am trying to use a LIKE query to search Artists, Albums, and Songs.
Right now I use the SQL below to grab the results from the three columns, then I use Ruby to bring them together in one object. I figure it would be much more efficient to use pure SQL rather than the interpreted language to return the results.
SELECT name FROM artists WHERE name LIKE 'something%'
SELECT name FROM albums WHERE name LIKE 'something%'
SELECT name FROM songs WHERE name LIKE 'something%'
I am not so great with SQL and have been struggling with this for a few days and was wondering if anyone on here could point me in the right direction.
You could, as others have suggested, use UNION. The semantics of UNION, however, force the database to eliminate duplicate rows which generally requires a sort operation. Since you know that each query necessarily returns non-duplicate rows, it would be more efficient to use UNION ALL. Something like
Whatever database engine you are using should be able to push the predicate on
NAMEinto each of the three branches that are being UNION ALL’ed together. But it would be worth confirming that in the query plan.