views:

66

answers:

2

Using Firebird:

I want to select a random entry in the table if the first SQL query returns 0 rows. Is there anyway to combine these two queries?

SELECT * FROM table WHERE cond=1;

SELECT FIRST 1 * FROM table ORDER BY rand();

Im using ExecuteNativeQuery on the java-side which takes basic SQL statements. Sadly, If-Else statements don't work. And if i could make a single query to the database instead of two, that would make my code appear faster.

A: 
if(exists(select 1 from table where cond=1))
SELECT * FROM table WHERE cond=1;
else
SELECT FIRST 1 * FROM table ORDER BY rand();

something like this, though I forgot whether the then keyword is needed in if statements in FirebirdSQL databases.

Alexander
Im using ExecuteNatieQuery on the java-side which takes basic SQL statements. Sadly, If-Else statements don't work. Thanks though.
Adrian
A: 

try this: Not sure but think it will work...

Select FIRST 1 t1.* 
FROM table t1
   left Join Table t2
      On t2.pk = t1.pk
         And t2.cond=1
ORDER BY Case When t2.Cond = 1 
              Then 0 Else rand() End  
Charles Bretana
Looks promising, but that where condition is where i get stuck. It returns 0 rows if the condition is not met. Also, is the order by and where conditions supposed to be reversed?
Adrian
ahhh yes, put condition in Join conditions... edited to fix...
Charles Bretana
It seems to bypass the condition, and just returns a random row.
Adrian
It should only do that if there is no row in the table with cond = 1. Check `Select * From table Where Cond = 1` and see what it returns...
Charles Bretana
the cond=1 does return a row.
Adrian
Ok nvm your query does work, however it returns two sets of rows, one from t1 and t2(left join, yea). t2 set is null if the condition isn't met, t1 always returns a random row. I guess i can work with that, thanks very much.
Adrian
I edited so it returns only one set of columns
Charles Bretana
if it is done that way, t1(the randomized set) will always show up, even when cond=1 exists. and will always give me the random row.
Adrian
ok, try the latest edited version...
Charles Bretana
It works perfectly, save the semi-colon after the cond=1. Your help is very appreciated. Thank you.
Adrian
@Adrian, yr welcome!
Charles Bretana