I want to make a compound query into MySQL. If the first part of the union is null, I want to return null; otherwise, I want to return the result of the union. Example:
IF( select * (select * from t1) as result, result UNION (select * from t2), "");
My line of code is not working. I get the following error:
Operand should contain 14 column(s)
Does anyone have any ideas how to do this corrrectly?
Thanks for the first reply below but it looks too expensive:
(SELECT * FROM t1)
UNION
( SELECT * FROM t2
WHERE EXISTS
( SELECT * FROM t1 )
)
My reason is t1 is actually a bunch of UNIONed statements itself. Is there a way to use something similar to an alias? The example below failed because the alias “result” is not carried across the UNION keyword.
SELECT * FROM ( large compound select statement) AS result
UNION
( SELECT * FROM t2
WHERE EXISTS
( SELECT 1 FROM result )
)
Thanks.
1 Answer