MySQL返回表名

5

假设我有这个MySQL表结构

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

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

有没有一种方法可以在这两个表中搜索字符串,然后如果字符串出现,则返回表的名称和行ID?

3个回答

3
假设两个表的id和新闻/内容具有相同的数据类型,那么查询语句应该类似于:
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%'

这应该可以给您所需的结果。


我只是猜测,但从表名来看,我想他想要搜索字符串作为子字符串,而不是精确匹配。 - Mark Byers
@kmunky,已更改以匹配您的确切要求 :) - Rob

1
你可以尝试这个:
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>%'

嗯...不知道为什么我的回答被踩了?有评论会很有帮助! - Dan Soap

1
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'

1
MySql 可能有点“性能不佳”(这是委婉的说法),因此,以这种形式查询,在两个表先聚合在一起的情况下,可能比我和 Cassy 发布的版本慢。遗憾的是,查询优化器远不如 Sql Server 的优化器好 =( - Rob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接