简体   繁体   English

搜索多个表-将结果列为一列

[英]Search in more than one table - give result as one column

Hey stackoverflow - This is my first question here. 嘿stackoverflow-这是我的第一个问题。

I have 2 tables in my mySQLdb. 我的mySQLdb中有2个表。

[tab_artist]
|id|artist|count  

[tab_songtitle]
|id|songtitle|artistId  

Im trying to select from both tab_artist.artist and tab_songtitle.songtitle as suggest where searchclause = m 我试图从tab_artist.artist和tab_songtitle.songtitle中选择作为建议,其中searchclause = m

I have tried this 我已经试过了

SELECT artist, songtitle AS suggest 
FROM tab_artist, tab_songtitle 
WHERE artist LIKE('m%') OR songtitle LIKE('m%')

But this gives me 2 columns, artist and suggest 但这给了我2个专栏,艺术家和建议

if the search is met i need artist to give me eg metallica.. but only once - but in songtitles i need all titles starting with met. 如果满足搜索条件,我需要艺术家给我,例如metallica ..,但是只有一次-但是在歌曲标题中,我需要所有以met开头的标题。

Hope this makes sence to the right expert :) 希望这对正确的专家有所帮助:)

A union should do it: union应该这样做:

select artist    AS suggest from tab_artist    WHERE artist    LIKE 'm%'
union all
select songtitle AS suggest from tab_songtitle WHERE songtitle LIKE 'm%'

For this case, I would use union all so you won't get duplicates removed, but you may want this if, for example, Metallica has a self-titled album and you only want the word to appear once. 对于这种情况,我将使用union all这样就不会删除重复项,但是例如,如果Metallica拥有一个自命名专辑并且您只希望单词出现一次,则可能需要这样做。 In that case, union would be more appropriate. 在这种情况下, union会更合适。

您需要加入:

Select artist, songtitle from tab_artist inner join tab_songtitle on tab_songtitle.artistID = tab_artist.ID where artist LIKe ('m%') OR songtitle like ('m%')

you want to use SQL UNION 您想使用SQL UNION

select id, artist, count FROM table1
UNION
select id, title, artistid from table2

It basically concats the two result sets vertically. 它基本上在垂直方向合并两个结果集。 There are some restrictions and modifications, but generally thats all you need to do. 有一些限制和修改,但是通常这就是您需要做的所有事情。

Use a UNION ALL to concatenate the results from the artist and song tables. 使用UNION ALL连接艺术家和歌曲表的结果。

SELECT 'Artist' AS type, id, artist AS suggest
FROM tab_artist
WHERE artist LIKE 'm%'
UNION ALL
SELECT 'Song', id, songtitle
FROM tab_songtitle
WHERE songtitle LIKE 'm%'

Don't use UNION as some are suggesting as that will do a completely unnecessary (and expensive) DISTINCT on the query results. 请勿像某些人建议的那样使用UNION ,因为这将对查询结果进行完全不必要(且昂贵)的DISTINCT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM