MySQL UNION - 检测几个SELECT返回结果的内容

时间:2011-03-20 20:57:00

标签: mysql sql union

我有两个与UNION合并的SELECT查询。这是MySQL查询:

SELECT `id`,`type`,`text`
  FROM my_table 
 WHERE position = '1' 
   AND status = '1' 
   AND targeting = 'all'
UNION
SELECT `id`,`type`,`text` 
  FROM my_table 
 WHERE position = '1' 
   AND status = '1' 
   AND targeting LIKE '%US%'

我怎样才能找出用TRUE执行的这两个SELECT查询的内容,以便从所需的行中获取结果?

1 个答案:

答案 0 :(得分:7)

您可以在查询中添加一个额外的列,根据查询的哪个部分成功返回不同的常量:

SELECT 'query1' AS `src`, `id`, `type`, `text`
FROM my_table
WHERE position = '1' AND status = '1' AND targeting = 'all'

UNION ALL

SELECT 'query2' AS `src`, `id`, `type`, `text`
FROM my_table
WHERE position = '1' AND status = '1' AND targeting LIKE '%US%'

同样在这种情况下,您根本不需要UNION:

SELECT
    targeting LIKE '%US%' AS `targeting_like_us`,
    targeting = 'all' AS `targeting_equals_all`,
    `id`,
    `type`,
    `text`
FROM my_table
WHERE position = '1'
AND status = '1'
AND (targeting LIKE '%US%' OR targeting = 'all')