我有三个简单的表格如下所示:
+----+-------------+ +----+-----------+ +----+---------------+
| artists | | albums | | songs |
+----+-------------+ +----+-----------+ +----+---------------+
| id | name | | id | name | | id | name |
+----+-------------+ +----+-----------+ +----+---------------+
| 0 | The Beatles | | 0 | Help! | | 0 | Help! |
| 1 | Metallica | | 1 | Metallica | | 1 | Enter Sandman |
+----+-------------+ +----+-----------+ +----+---------------+
我希望查询结果如下:
+--------+---------------+
| type | name |
+--------+---------------+
| artist | The Beatles |
| artist | Metallica |
| album | Help! |
| album | Metallica |
| song | Help! |
| song | Enter Sandman |
+--------+---------------+
我正在尝试使用LIKE
查询来搜索艺术家,专辑和歌曲。
现在我使用下面的SQL从三列中获取结果,然后我使用Ruby将它们组合在一个对象中。我认为使用纯SQL而不是解释语言返回结果会更有效。
SELECT name FROM artists WHERE name LIKE 'something%'
SELECT name FROM albums WHERE name LIKE 'something%'
SELECT name FROM songs WHERE name LIKE 'something%'
我对SQL并不是很好,并且几天来一直在努力解决这个问题,并且想知道这里是否有人能指出我正确的方向。
答案 0 :(得分:2)
您可以使用UNION将类似的结果合并在一起。试试这个:
SELECT 'artist' as Type, name FROM artists WHERE name LIKE 'something%'
UNION SELECT 'album' as Type, name FROM albums WHERE name LIKE 'something%'
UNION SELECT 'song' as Type, name FROM songs WHERE name LIKE 'something%'
答案 1 :(得分:1)
您应该使用union在单个结果集中合并结果,并根据表格对您想要的类型进行硬编码。
SELECT 'artist' as [type], name FROM artists WHERE name LIKE 'something%'
UNION
SELECT 'album' as [type], name FROM albums WHERE name LIKE 'something%'
UNION
SELECT 'song' as [type], name FROM songs WHERE name LIKE 'something%'
答案 2 :(得分:1)
使用带有常量字符串的union作为结果的列,例如
select 'artist' as type, name as name from artists
union select 'album' as type, name as name from albums
union select 'song' as type, name as name from songs
答案 3 :(得分:1)
您可以像其他人所建议的那样使用UNION。但是,UNION的语义强制数据库消除通常需要排序操作的重复行。由于您知道每个查询都必须返回非重复行,因此使用UNION ALL会更有效。像
这样的东西SELECT *
FROM (SELECT 'artists' as type, name
FROM artists
UNION ALL
SELECT 'albums' as type, name
FROM albums
UNION ALL
SELECT 'songs' as type, name
FROM songs)
WHERE name LIKE 'something%'
无论您使用什么数据库引擎,都应该能够将NAME
上的谓词推送到一起进行UNION ALL的三个分支中的每个分支。但是在查询计划中确实值得确认。
答案 4 :(得分:0)
select 'artists' as type, name from artists where name like '%something%'
union
select 'albums' , name from albums where ...
union
select 'songs', name from songs where ...