4

I have a situation where I need to execute two different queries in MySql is it possible to do so in MySql. It is select query.

 eg. Query1:  Select * from table1
     Query2: Select * from table2

Now how do I execute these query

conditonally

select * from if(somecondition ) then Query 1 else query 2
1
  • 2
    There is such a thing as an IF() control flow function. However, it is difficult to tell whether this is what you need. I think you'll have to provide examples of data, table structure and desired output. Commented Jul 11, 2011 at 9:10

2 Answers 2

3
IF MyCondition = True THEN
  Select * from table1;
ELSE
  Select * from table2;
END IF;

Reference

Sign up to request clarification or add additional context in comments.

9 Comments

I think this is what you want. If you're wanting to branch from inside of a single query, I think you will be disappointed, because TableA and TableB could have different columns and it is my understanding that the DB Server must know which columns will come back from a subquery.
This would have to be inside of a stored procedure. Having different columns is not a problem either, unless your code isn't prepared to deal with that situation.
@hamlin Thanks. @siride I don't want stored procedure though
@Kitex: then don't use this method. Perhaps you should just do two queries from your program, one to evaluate the condition and the second to run one or the other queries, based on the results of your condition.
You must use a stored procedure or function if you want to use IF / ELSE / END IF apparently. Sorry @Kitex! So, if you want to use this answer, you'll need to put it into a SP.
|
0

i think this can be done using union , i do have a small example to share hope it helps...

Example:

SELECT TEXT,language 
FROM TABLE 
WHERE LANGUAGE = 'spanish'
union all
select text,language
from TABLE as t
where language = 'english'
and not exists
(select *
 from table
 where language = 'spanish'
 and table.pid = t.pid)

2 Comments

That's not really a conditional though.
@Thanks but not my requirement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.