2011-06-20 40 views
3

我有三个简单的表,如下图所示:结合多列

+----+-------------+ +----+-----------+ +----+---------------+ 
| 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如此之大,并已与此挣扎了几天,想知道如果在这里任何人都可以在正确的方向指向我。

回答

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'ed在一起。但是在查询计划中值得确认。

+0

我正在考虑如何与其他答案完全一致。好样的! – RyanScottLewis

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%' 
+0

我以前实际遇到过这个答案。这里的问题是我需要知道每个结果实际在哪个表中。尽管感谢您的快速回答!编辑:Bah,我错过了查询的“AS”部分。 = p – RyanScottLewis

1

您应该使用工会单个ResultSet合并的结果,同时也硬编码您可以根据表要的类型..

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%' 
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 ... 
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