简体   繁体   English

SQL:如果条件为假,则获取随机条目

[英]SQL: Get a random entry iff condition is false

Using Firebird: 使用Firebird:

I want to select a random entry in the table if the first SQL query returns 0 rows. 如果第一个SQL查询返回0行,我想在表中选择一个随机条目。 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. 我在使用基本SQL语句的Java端使用ExecuteNativeQuery。 Sadly, If-Else statements don't work. 可悲的是,If-Else语句不起作用。 And if i could make a single query to the database instead of two, that would make my code appear faster. 如果我可以对数据库进行单个查询而不是两个查询,那将使我的代码显示得更快。

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. 像这样的事情,尽管我忘记了FirebirdSQL数据库中的if语句中是否需要then关键字。

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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM