2017-07-12 15 views
0

私はこのクエリが正確に何を実行するのか把握しようとしています。特に、変数@と割り当て:=が使用されている部分です。 派生テーブルt1からネストされたクエリがあるので、最初の部分は非常に単純ですが、わからないのは列の結果rです。このmysqlクエリは何を意味しますか?

SELECT 
t1.user_id, 
t1.percentage, 
t1.id, 
t1.name, 
(@rn := if(@uid = t1.user_id, @rn + 1, 
    if(@uid := t1.user_id, 1, 1)) 
) as rn 

FROM 

(SELECT 
pbt.user_id, 
pbt.percentage, 
t.id, t.name 
FROM 
user_purchased_brand_tags AS pbt 
JOIN tags t on t.id = pbt.tag_id 
ORDER BY pbt.user_id, pbt.percentage desc) t1 
+0

の値を入力してくださいeのGoogleや疑問のマニュアルは、また、それについてのstackoverflowの質問にたくさんある、例えば:https://stackoverflow.com/questions/37869719/difference-between-and https://stackoverflow.com/質問/ 39379659/what-does-the-operator-mean-in-mysql – Ryosaku

答えて

1

user_idが変更されると、1にリセットされる行番号が作成されます。

if関数のパラメータは(条件、真部分、偽部分)です。

(@rn := /* assign the new value to the variable @rn */ 

if(@uid = t1.user_id, @rn + 1, /* when user_id is the same as the value in @uid, return @rn + 1. 
            The comparison is done before assigning the value of the current row below. Therefore the @uid variable still holds the value of the previous row */ 

    if(@uid := t1.user_id, 1, 1)) /* this applies when above condition is not true. 
            It's a clever combination of assigning the value of the current row to @uid and returning 1 at the same time. */ 

) as rn 
+0

ありがとうございます!これは私が探していた答えです – UgoL

1

:=この

(発現、expression_if_true、expression_if_false)IF等assignement operator

IF() function作品です。

は、この:@rn

if (@uid == t1.user_id) { // <------ t1.user_id is COMPARED with @uid 

    @rn = @rn + 1 ; // or @rn++, ie we increment it by 1 

}else{ 

     if (@uid = t1.user_id) { // <------ t1.user_id is ASSIGNED to @uid 

      @rn = 1; 

     }else{ 

      @rn = 1; 

     } 

} 

場合割り当て常に同じ値1が、それはまた割り当てる:

@rn := if(@uid = t1.user_id, @rn + 1, 
    if(@uid := t1.user_id, 1, 1)) 

は、PHP/Cのスタイルでそのように分解することができます。 t1.user_id@uid

関連する問題