我正在试图找出这个查询的确切执行情况。特别是在其中使用变量@
和赋值:=
的部分。
第一部分非常简单,因为我们有一个来自派生表t1的嵌套查询,但对我来说不太清楚的是列rn的结果。这是查询:
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 :(得分:1)
当user_id发生变化时,它会创建一个重置为1的行号。
if函数的参数是(condition,true part,false part)。
(@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
答案 1 :(得分:1)
@rn := if(@uid = t1.user_id, @rn + 1,
if(@uid := t1.user_id, 1, 1))
是
IF(表达式,expression_if_true,expression_if_false);
此:
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;
}
}
可以像PHP / C风格那样分解:
@rn
第二个 if 始终将相同的值1分配给t1.user_id
,但它还将@uid
的值分配给{{1}}