mysql, ASC a series of number using existed data(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 使用现有数据的一系列数字
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
