开发者

MySQL UNION - detect what of several SELECTs return result

开发者 https://www.devze.com 2023-02-18 10:26 出处:网络
I have two SELECT queries merged with UNION. Here is MySQL query: SELECT `id`,`type`,`text` FROM my_table

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')
0

精彩评论

暂无评论...
验证码 换一张
取 消