views:

49

answers:

3

let's say i have this mysql table structure:

table : articles
----------------
id
content

table : news
------------
id
news

is there a way to search for a string in this two tables and then if the string occurs to return the table's name and the row id ?

+3  A: 

Assuming that the two tables have the same datatypes for id and news/content then a query along the lines of

SELECT id, 'articles' as tablename
WHERE content like '%string to search for%'
UNION
SELECT id, 'news' as tablename
WHERE news like '%string to search for%'

Should give you the result you're after

Rob
I'm just guessing here, but from the table names I imagine that he wants to search for the string as a substring, not as an exact match.
Mark Byers
yup, you're right
kmunky
@kmunky, changed it to match your exact requirement :)
Rob
+1  A: 

You could try this:

SELECT 'articles' as table_name, id
FROM `articles` 
WHERE content like '%<my_string>%'

UNION

SELECT 'news' as table_name, id 
FROM `news` 
WHERE news like '%<my_string>%'
Cassy
Humm ... wondering why my answer got a downvote ? Comments would be helpful!
Cassy
+1  A: 
SELECT * FROM (

SELECT id, content as text, 'articles' as tablename
FROM articles

UNION ALL

SELECT  id, news as text, 'news' as tablename
FROM news

) as tmp 

WHERE text = 'SEARCH_TERM'
Rifat
MySql can be a bit "non-performant" (that's the polite way of putting it), so a query in this form where the two tables are aggregated together first could be slower than the version myself and Cassy posted. Sadly the query optimiser isn't anywhere near as good as the Sql Server one =(
Rob
ya, you are right.
Rifat