1. 程式人生 > >資料庫中隨機查詢一條記錄的SQL

資料庫中隨機查詢一條記錄的SQL

資料庫的隨機查詢SQL 
 
1. Oracle,隨機查詢20條


select * from


(
 select  *  from 表名
 order by dbms_random.value


)
 where rownum <= 20;


 


2.MS SQL Server,隨機查詢20條


select top 20  * from  表名order by newid()


 


3.My SQL:,隨機查詢20條


select  *  from  表名 order by rand() limit 20


 


隨機查詢指定人員的一條未讀訊息
 
幫助訊息表 S_MSG_HINT
幫助訊息ID SMH_ID NUMBER(20) PK
幫助訊息內容 SMH_TEXT VARCHAR2(200)
 
人員幫助訊息表 S_HINTPEOPLE
人員ID SHP_UID VARCHAR2(20) PK
當前幫助訊息ID SMH_ID NUMBER(20)  PK FK
 
如果為已讀訊息會在 人員幫助訊息表裡面生成記錄
 
select
    *
from
    (select
        smh.*,
        nvl2( shp.smh_id,1,0) as status --0:未讀 1:已讀
    from
        s_msg_hint smh
                left join s_hintpeople shp 
                    on smh.smh_id = shp.smh_id 
                    and shp.shp_uid = 'p_chencc'
    order by
        dbms_random.value  --隨機數值排序
    )
where
    status = 0 and --未讀訊息
    rownum <= 1  --取一條