mysql, ASC 使用现有数据的一系列数字

mysql, ASC a series of number using existed data(mysql, ASC 使用现有数据的一系列数字)

本文介绍了mysql, ASC 使用现有数据的一系列数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,我有这个查询,它按数字大的顺序排列我的数据

Good day, I have this query which arrange my data in order of higher number

SELECT username,count(*) as description
FROM products
WHERE
description LIKE '%Yes%'

or

description LIKE '%yes%'
GROUP BY username
ORDER BY description ASC

这会给我带来这个结果

username  |   description
   a      |     3
   b      |     1

我能够做到以上几点,问题是我应该怎么做才能做到这一点?

I'm able to do the above, question is what should I do in order to make it like this?

 rank   |   username    |  description
  1     |     a         |    3
  2     |     b         |    1

新列,rank,它是一个固定的 1,2,3,不会随着用户名和描述名称的变化而变化.

new column, rank, which is a fixed 1,2,3 that won't change while the username and description name change.

推荐答案

我知道在使用带有 group by 的变量时有时会出现问题.我不确定这是否会影响计数变量,但它肯定会影响运行总和.更安全的方法是使用子查询:

I know there are sometimes issues when using variables with group by. I'm not sure if this affects counting variables, but it definitely affects running sums. A safer approach is to use a subquery:

SELECT (@rn := @rn + 1) as rank, username, numdescription
FROM (SELECT p.username, count(*) as numdescription
      FROM products p
      WHERE description LIKE '%Yes%' or description LIKE '%yes%'
      GROUP BY p.username
     ) p CROSS JOIN
     (SELECT @rn := 0) vars
ORDER BY numdescription DESC;

请注意,我重命名了输出字段.使用相同的名称似乎令人困惑,因为一个是描述(字符串),另一个是计数(数字).

Note that I renamed the output field. Using the same name seems confusing, because one is a description (string) and the other is a count (number).

这篇关于mysql, ASC 使用现有数据的一系列数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:mysql, ASC 使用现有数据的一系列数字

基础教程推荐