2015/4/9

SQL查詢TABLE內連續出現3次的指令



From:

http://www.blogjava.net/changedi/archive/2015/01/29/422554.html

節錄:
discuss區找到了一個很讚的解法,通過定義變量,很巧妙的解了這個擴展的問題,原作者kent-huang

select DISTINCT num
FROM (
  select
    num,
    case when @record = num then @count:=@count+1
         when @record <> @record:=num then @count:=1
    end as n
  from Logs ,(
    select
       @count:=0,
       @record:=(SELECT num from Logs limit 0,1)
  ) r
) a
where a.n>=3

簡單分析一下,作者通過定義兩個變量recordcount來控制記錄和對應的rank值,首先通過一個select @count:=0,@record:=(SELECT num from Logs limit 0,1)語句來初始化這兩個變量count=0record=表裡第一條記錄的num。接下來通過普通查詢,將Logs表裡每一條記錄查出來,和record對比,如果相同,則count自增1,如果不同,那麼新的record被賦值,同時count1,很漂亮的自定義變量用sql實現了我們直覺上需要用邏輯代碼來完成的功能。而且這個代碼的一大優勢是不需要用到Id字段~~非常棒

沒有留言:

JPA+complex key+custom Query

  來源: https://www.cnblogs.com/520playboy/p/6512592.html   整個來說,就是有複合主鍵 然後要使用  public interface XxXXxx DAO extends CrudRepository<Tc...