我有两个 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%'
同样在这种情况下,您根本不需要 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')
关于MySQL UNION - 检测几个 SELECT 的返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5371447/