简体   繁体   English

模仿session_num的MySQL会话变量的值没有增加

[英]Mysql session variable emulating row_num does not increase in value

Since MySql does not provide a row_num facility, I was trying to emulate its functionality using session variables (@variable_name) in my query 由于MySql不提供row_num工具,因此我试图在查询中使用会话变量(@variable_name)来模拟其功能。

the problem statement is as follows Given a table 'product_view' having columns 'productTitle' and 'categoryName', select the first 2 products from each category whose title matches a provided string Going by the following query 问题陈述如下:给定一个表'product_view'包含列'productTitle'和'categoryName',请从每个类别中选择标题与提供的字符串匹配的前两个产品。

SELECT
  @row_num := CASE
                WHEN @cat_name = categoryName THEN @row_num + 1
                ELSE 1
              END 
  AS num,
  @cat_name := categoryName AS categoryName,
  productTitle
FROM product_search
WHERE 
  cityId = 1 AND
  mainStatus= 'Active' AND
  stock_status = 'In Stock' AND
  prodQuantity != 0 AND 
  productTitle LIKE '%apple%'
ORDER BY categoryName, LOCATE('apple', productTitle), productTitle

This is expected to give row_num values 1,2 for category1 and 1,2 for category 2 and so on (wherever ther is a match for 'Apple'). 预期这将为类别1提供row_num值1,2,为类别2提供1,2,依此类推(以此类推)。 But the rownum value is always stuck at 1 但是rownum值始终停留在1

Something similar on the fiddle below FIDDLE FIDDLE下面的小提琴中有类似的东西

Can someone please help me out on this 有人可以帮我这个忙吗

In more recent versions of MySQL, you need to do the order by in a subquery. 在最新版本的MySQL中,您需要在子查询中进行order by

In addition, you cannot set @cat_name in one expression and use it in another. 另外,您不能在一个表达式中设置@cat_name ,而在另一个表达式中使用它。 MySQL does not guarantee the order of evaluation of expressions in a SELECT . MySQL不保证SELECT中表达式的求值顺序。 So, you don't know which gets evaluated first, the assignment or the comparison. 因此,您不知道首先评估哪个,赋值或比较。

I usually write this as: 我通常这样写:

SELECT (@rn := IF(@cat_name = categoryName, @rn + 1,
                  IF(@cat_name := categoryName, 1, 1)
                 )
       ) as num,
       categoryName, productTitle
FROM (SELECT ps.*
      FROM product_search ps
      WHERE cityId = 1 AND
            mainStatus= 'Active' AND
            stock_status = 'In Stock' AND
            prodQuantity <> 0 AND 
            productTitle LIKE '%apple%'
      ORDER BY categoryName, LOCATE('apple', productTitle), productTitle
     ) ps CROSS JOIN
     (SELECT @cat_name := '', @rn := 0) params

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM