2017-07-12 111 views
0

我想弄清楚這個查詢究竟執行什麼。特別是部分在其中使用的變量@和分配:=。 第一部分是很簡單,因爲我們從派生表T1嵌套查詢,但什麼是不是真的清楚,我是RN列的結果。這裏的查詢:這個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中的谷歌或手動的疑慮,並也有很多關於它的問題計算器,例如:https://stackoverflow.com/questions/37869719/difference-between-and或https://stackoverflow.com/問題/ 39379659/what-does-operator-mean-in-mysql – Ryosaku

回答

1

它創建重置爲1個時,USER_ID變化的行號。

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

:=assignement operator

IF() function作品這樣

IF(表達式,expression_if_true,expression_if_false);

此:

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

可以像在PHP/C式分解:

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但它也分配的t1.user_id價值@uid