MySQL UNION - detect what of several SELECTs return result
I have two SELECT queries merged with UNION. Here is MySQL query:
SELECT `id`,`type`,`text`
FROM my_table
WHERE position = '1'
AND status = '1'
AND target开发者_JS百科ing = 'all'
UNION
SELECT `id`,`type`,`text`
FROM my_table
WHERE position = '1'
AND status = '1'
AND targeting LIKE '%US%'
How can I find out what of these two SELECT queries executed with TRUE in order to fetch result from needed row?
You can add an extra column to your query that returns a different constant depending on which part of the query succeeded:
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%'
Also in this case you don't need a UNION at all:
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')
精彩评论