选择使用UNION ALL疑问

时间:2011-09-08 08:22:44

标签: mysql select union

我正在使用UNION ALL进行搜索页面的选择,所以我需要知道结果来自哪个表,为我做一个指向正确页面的链接。 有可能吗?

例如:

(SELECT id, title AS tit FROM video WHERE `title` LIKE '%test%')
UNION ALL
(SELECT id, title AS tit FROM testimonials WHERE `title` LIKE '%test%' AND _type = 'news')
UNION ALL
(SELECT id, title AS tit FROM image_gallery  WHERE `title` LIKE '%test%' AND id_gallery = '1')

干杯芒果

2 个答案:

答案 0 :(得分:4)

只需将表名添加到每个子查询中:

(SELECT 'video' as tablename, id, title AS tit 
 FROM video 
 WHERE `title` LIKE '%test%')
 UNION ALL
(SELECT 'testimonials' as tablename, id, title AS tit 
 FROM testimonials 
 WHERE `title` LIKE '%test%' AND _type = 'news')
 UNION ALL
(SELECT 'image_gallery' as tablename, id, title AS tit 
 FROM image_gallery
 WHERE `title` LIKE '%test%' AND id_gallery = '1')

答案 1 :(得分:2)

如何将表名添加到SELECT语句中?

(SELECT id, title AS tit, 'video' as tname FROM video WHERE `title` LIKE '%test%')
UNION ALL
(SELECT id, title AS tit, 'testimonials' as tname FROM testimonials WHERE `title` LIKE '%test%' AND _type = 'news')
UNION ALL
(SELECT id, title AS tit, 'image_gallery' as tname FROM image_gallery  WHERE `title` LIKE '%test%' AND id_gallery = '1')