2014-02-18 53 views
0

DB2 SQL我有一個表Test_Person和Test_Person_Details隨機和限價

Test_Person 
ID (PrimaryKey) 
STATUS "NEW/OLD" 

Test_Person_Details 
ID (FK) 
NAME 
AGE 
DESC 
... 

我一定要得到隨機10名的特定ID WHERE狀態是「新」。什麼是DB2中的查詢?

回答

2

這是一個緩慢的方式:

select pd.name 
from (select p.* 
     from test_person p 
     order by rand() 
     fetch first 10 rows only 
    ) p join 
    test_person_details pd 
    on p.id = pd.id; 

如果你的表中有超過1000行,你可以做更有效率:

select pd.name 
from (select p.* 
     from test_person p tablesample bernoulli(1) 
     order by rand() 
     fetch first 10 rows only 
    ) p join 
    test_person_details pd 
    on p.id = pd.id; 
+0

第二屆查詢可能是特定於LUW。 – WarrenT