mysql数据库 实现类似标记序号的伪列_MySQL
Jun 01, 2016 pm 01:44 PMbitsCN.com
在查询数据库的时候,我们有时候需要对查询出来的数据加上序列,1,2,3,……n
例如:我们根据表的某个字段排序后,要对这些数据加上序列,这个时候序号常常不是我们建表时设置好的自增的主键id,怎么办呢????
可能我们会用变量来解决,如下
set @rownum=0;
SELECT @rownum:=@rownum+1 AS rownum, table_name.*
FROM table_name
如果在数据库中要用一句SQL语句来实现,这又改怎么办呢????
oracle数据库有专门的rownum来解决伪序列问题,但是mysql却到目前为止还没有内置的函数等来解决此问题
这个问题也困扰了我一段时间,到各种论坛上发帖也没有能回答,最后在无意间找到了这种解决方法
SELECT @rownum:=@rownum+1 AS rownum, table_name.*
FROM (SELECT @rownum:=0) r, table_name
把rownum的设置初值放到了from 和需要查询的表的前面
原文来自“老鸟的大心脏”,在这里谢谢他。
希望能帮助更多需要帮助的人……
也希望更多的高手们提出更多的漂亮的方法……
也许有人也会用到存储过程来解决,那也是一个方法,我曾经也用过,但是后来不能用存储过程了,就悲剧了
摘自 ystyaoshengting的专栏
bitsCN.com
Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How does Go language implement the addition, deletion, modification and query operations of the database?

Detailed tutorial on establishing a database connection using MySQLi in PHP

Comparison of similarities and differences between MySQL and PL/SQL

How does Hibernate implement polymorphic mapping?

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos

An in-depth analysis of how HTML reads the database

Analysis of the basic principles of MySQL database management system

Tips and practices for handling Chinese garbled characters in databases with PHP
