0

I have a number of queries that contain multiple columns and I would like to run a single query to test them in order until one subquery returns results. I have found that a COALESCE statement only allows you to use and return a single column per sub query, which will not work with my data set:

subquery1 = SELECT col1, col2, col3 FROM table1 WHERE x = y
subquery2 = SELECT col2, col4, col7 FROM table2 WHERE t = p
subquery3 = SELECT col5, col8, col9 FROM table3 WHERE v = b

Is it possible to test each of these queries in order until one of them returns rows?

somecallmemike
  • 441
  • 1
  • 8
  • 19

2 Answers2

0
SELECT  1 AS o, col1, col2, col3
FROM    table1
WHERE   x = y
UNION ALL
SELECT  2 AS o, col2, col4, col7
FROM    table2
WHERE   t = p
UNION ALL
SELECT  3 AS o, col5, col8, col9
FROM    table3
WHERE   v = b
ORDER BY
        o
LIMIT   1
Quassnoi
  • 413,100
  • 91
  • 616
  • 614
0

If you want to return only the first query with rows, then you should write a procedure:

delimiter $$
create procedure myProc()
begin
    if exists(SELECT col1, col2, col3 FROM table1 WHERE x = y) then
        SELECT col1, col2, col3 FROM table1 WHERE x = y;
    elseif exists(SELECT col2, col4, col7 FROM table2 WHERE t = p) then
        SELECT col2, col4, col7 FROM table2 WHERE t = p;
    elseif exists(SELECT col5, col8, col9 FROM table3 WHERE v = b) then
        SELECT col5, col8, col9 FROM table3 WHERE v = b;
    end if;
end $$
delimiter ;

And then call it:

call myProc();
Barranka
  • 20,547
  • 13
  • 65
  • 83