Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching Multiple Tables (SQL)

Tags:

sql

php

mysql

I need to be able to have an SQL query that searches my database using a simple search. Here is what my tables look like right now:

Table artists
--------------
id
name

Table albums
-------------
id
artistID
name

Table songs
------------
id
albumID
name

How would I go about doing this? Here are some SQL queries that I have tried, but my issue is that it is returning a lot of data. For instance, if I search for an artist like Snoop Dogg, it is returning a row for each album and song that he has even if they don't contain his name.

SELECT * FROM artist,album,songs WHERE artist.name LIKE '%snoop%' OR albums.name LIKE '%snoop%' OR songs.name LIKE '%snoop%';

Edit:

Here is a sample database;

artists
-----------
1 | Snoop Dogg
2 | Linkin Park

albums
--------
1 | artist=1 | Boom
2 | artist=2 | ThisIsIt

songs
--------
1 | album=1 | First
2 | album=2 | Second Linkin
3 | album=2 | Third
4 | album=1 | Fourth

So I want a search for "snoop" to return just the artist "Snoop Dogg". But then a search like "Linkin" to return the artist and the song.

like image 498
Flipper Avatar asked May 07 '26 17:05

Flipper


1 Answers

This query will retrieve matching artists, songs and albums. First column gives a clue about origin of the data, second is id and the last is the name.

select 'Artists' OriginatingTable, id, name
  from artists
 where name like '%snoop%'
union all
select 'Albums', id, name
  from albums
 where name like '%snoop%'
union all
select 'Songs', id, name
  from songs
 where name like '%snoop%'
like image 80
Nikola Markovinović Avatar answered May 10 '26 08:05

Nikola Markovinović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!