我有两个SELECT查询与UNION合并。以下是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%'

如何找出这两个SELECT查询中使用TRUE执行的查询,以便从所需的行中获取结果?

最佳答案

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

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

在这种情况下,你根本不需要工会:
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')

10-06 08:50