搜索多个表 (SQL)

Fli*_*per 2 php mysql sql

我需要能够使用简单的搜索来搜索我的数据库的 SQL 查询。这是我的表现在的样子:

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

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

Table songs
------------
id
albumID
name
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?以下是我尝试过的一些 SQL 查询,但我的问题是它返回了大量数据。例如,如果我搜索像 Snoop Dogg 这样的艺术家,它会为他拥有的每张专辑和歌曲返回一行,即使它们不包含他的名字。

SELECT * FROM artist,album,songs WHERE artist.name LIKE '%snoop%' OR albums.name LIKE '%snoop%' OR songs.name LIKE '%snoop%';
Run Code Online (Sandbox Code Playgroud)

编辑:

这是一个示例数据库;

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
Run Code Online (Sandbox Code Playgroud)

所以我想搜索“snoop”来只返回艺术家“Snoop Dogg”。但是然后像“Linkin”这样的搜索来返回艺术家和歌曲。

Nik*_*vić 5

此查询将检索匹配的艺术家、歌曲和专辑。第一列给出了有关数据来源的线索,第二列是 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%'
Run Code Online (Sandbox Code Playgroud)


Tad*_*eck 5

以下使用UNION,从而避免JOINs:

(
    SELECT
        'artist' as `type`,
        `artists`.`id` as `id`,
        `artists`.`name` as `name`
    FROM `artists`
    WHERE
        `artists`.`name` LIKE '%snoop%'
)
UNION
(
    SELECT
        'album' as `type`,
        `albums`.`id` as `id`,
        `albums`.`name` as `name`
    FROM `albums`
    WHERE
        `albums`.`name` LIKE '%snoop%'
)
UNION
(
    SELECT
        'song' as `type`,
        `songs`.`id` as `id`,
        `songs`.`name` as `name`
    FROM `songs`
    WHERE
        `songs`.`name` LIKE '%snoop%'
)
Run Code Online (Sandbox Code Playgroud)