我需要能够使用一个简单的搜索来搜索我的数据库的 SQL 查询。这是我的表格现在的样子:
Table artists
--------------
id
name
Table albums
-------------
id
artistID
name
Table songs
------------
id
albumID
name
我该怎么做呢?这是我尝试过的一些 SQL 查询,但我的问题是它返回了大量数据。例如,如果我搜索像 Snoop Dogg 这样的艺术家,它会为他拥有的每张专辑和歌曲返回一行,即使它们不包含他的名字也是如此。
SELECT * FROM artist,album,songs WHERE artist.name LIKE '%snoop%' OR albums.name LIKE '%snoop%' OR songs.name LIKE '%snoop%';
编辑:
这是一个示例数据库;
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
所以我想搜索“snoop”以仅返回艺术家“Snoop Dogg”。但随后像“Linkin”这样的搜索会返回艺术家和歌曲。
最佳答案
此查询将检索匹配的艺术家、歌曲和专辑。第一列提供有关数据来源的线索,第二列是 ID,最后是名称。
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%'
关于php - 搜索多个表 (SQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9814522/