tags:

views:

75

answers:

4

Hey stackoverflow - This is my first question here.

I have 2 tables in my mySQLdb.

[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

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

if the search is met i need artist to give me e.g. metallica.. but only once - but in songtitles i need all titles starting with met.

Hope this makes sence to the right expert :)

+2  A: 

A union should do it:

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. In that case, union would be more appropriate.

paxdiablo
That's just excactly what I want :) thx alot and thx for your interrest in my question to all three of you :)
fjappe
I get your point. But how do i make sure that if e.g. metallica has a titletrack called metallica that i only the the word once?
fjappe
Use union instead of union all - it will remove the duplicates.
paxdiablo
Thx alot - I think it's working as intended now.
fjappe
A: 

you want to use 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.

Richard Levasseur
A: 

Use a UNION ALL to concatenate the results from the artist and song tables.

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.

cletus
This is what i have now: select distinct(artist) AS suggest from tab_artist WHERE artist LIKE('ma%')union allselect distinct(songtitle) AS suggest from tab_songtitle WHERE songtitle LIKE('ma%')Would that give me metallica only once, even if theres an artist and a songtitle named metallica ?
fjappe
+1  A: 

You need a join:

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%')
GrayWizardx
I did not read the one column part, please disregard my answer.
GrayWizardx
np, thanks anyway :)
fjappe