嘿stackoverflow - 这是我的第一个问题。
我的mySQLdb中有2个表。
[tab_artist]
|id|artist|count
[tab_songtitle]
|id|songtitle|artistId
我试图从tab_artist.artist和tab_songtitle.songtitle中选择作为建议,其中searchclause = m
我试过这个
SELECT artist, songtitle AS suggest
FROM tab_artist, tab_songtitle
WHERE artist LIKE('m%') OR songtitle LIKE('m%')
但这给了我2列,艺术家和建议
如果符合搜索条件,我需要艺术家给我,例如metallica ..但只有一次 - 但在歌曲中我需要以met开头的所有标题。
希望这能让他们找到合适的专家:)
答案 0 :(得分:2)
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%'
对于这种情况,我会使用union all
,因此您不会删除重复项,但如果Metallica有一个自我标题的专辑而您只希望该单词出现一次,那么您可能需要这样做。在这种情况下,union
会更合适。
答案 1 :(得分:1)
您需要加入:
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%')
答案 2 :(得分:0)
您想使用SQL UNION
select id, artist, count FROM table1
UNION
select id, title, artistid from table2
它基本上垂直地连接两个结果集。有一些限制和修改,但通常都是你需要做的。
答案 3 :(得分:0)
使用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%'
不要像某些人所说的那样使用UNION
,因为这会对查询结果执行完全不必要(且代价高昂)的DISTINCT
。