2017-07-12 112 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