这个mysql查询是什么意思?
我试图弄清楚这个查询到底执行什么。特别是使用变量这个mysql查询是什么意思?,mysql,sql,database,Mysql,Sql,Database,我试图弄清楚这个查询到底执行什么。特别是使用变量@和赋值:=的部分。 第一部分非常简单,因为我们有一个来自派生表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,
@
和赋值:=
的部分。
第一部分非常简单,因为我们有一个来自派生表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
它创建一个行号,当用户id更改时,该行号将重置为1 if函数的参数为(条件、真部、假部)
它创建一个行号,当用户id更改时,该行号将重置为1 if函数的参数为(条件、真部、假部)
:=
是一个
是这样工作的
IF(表达式,表达式如果为真,表达式如果为假)
这:
可以像PHP/C样式那样分解:
如果(@uid==t1.user_id){/:=
是
是这样工作的
IF(表达式,表达式如果为真,表达式如果为假)
这:
可以像PHP/C样式那样分解:
if(@uid==t1.user\u id){//你应该使用谷歌或手册来解答疑问,在stackoverflow中也有很多关于它的问题,例如:或者你应该使用谷歌或手册来解答疑问,在stackoverflow中也有很多关于它的问题,例如:或者谢谢!这是我搜索的答案谢谢!这是答案我一直在寻找的
(@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
@rn := if(@uid = t1.user_id, @rn + 1,
if(@uid := t1.user_id, 1, 1))