1. 程式人生 > 其它 >各類SQL語句彙總

各類SQL語句彙總

技術標籤:資料庫mysqlsql


1.將結果進行排序後,對排序後的資料進行排名

select 
t.score Score,
CAST((case when @rowtotal = t.score then @rownum:=@rownum + 0
      when @rowtotal := t.score then @rownum:=@rownum + 1
      when @rowtotal = 0 then @rownum:=@rownum+1 end) AS SIGNED) as `Rank` from 
(select score from scores order by
score desc) t, (select @rownum:=0,@rowtotal:=null)c

其中case when的語句解釋如下:

  • 第一個when是判斷當前的score是否等於當前賦值的@rowtotal,如果是,則排名不變(排名並列)
  • 一開始的時候,第一個when是不會執行的,因為此時@rowtotal為null,而到了第二個when的時候@rowtotal := score將score賦值給了@rowtotal,只要score>0,那麼改判斷都為true,就將@rownum行號+1。
  • 第三個when只有當第二個when將@rowtotal賦值為0的時候,才會執行。


2.刪除語句聯表查詢

delete from table1 t1,table2 t2 where t1.id > t2.id and t1.email = t2.email;

該語句時錯誤的,執行後會報錯,應該寫成以下的方式

delete t1 from table1 t1,table2 t2 where t1.id > t2.id and t1.email = t2.email;

兩張表關聯查詢的話,就需要制定好要刪除哪張表。

後續有其他的SQL語句,再來繼續新增