Home >Backend Development >PHP Tutorial >How to add automatic numbers to query results_PHP tutorial

How to add automatic numbers to query results_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-13 17:01:211155browse

There is often such a requirement. I need to add a column of numbers similar to Identity in the query results. Although it is not difficult to implement in Client programming, sometimes I want to keep the existing Class and do not want to do additional work on the Client side. coding, then the only way is to find a way in Sql
First of all, I will introduce a way to complete it with a SQL statement. The principle is to query the number of records greater than or equal to the record in the result, and you can get its Rank
Example:
USE pubs
SELECT COUNT(*) AS Rank, a1.au_lname, a1.au_fname
FROM authors a1, authors a2
WHERE a1.au_lname a1.au_fname >= a2. au_lname a2.au_fname
GROUP BY a1.au_lname, a1.au_fname
ORDER BY Rank
However, this method has its limitations. The first is poor performance, and the second is if the same records, then the Rank will be tied, for example, two 2s appear, but there is no 3
Is there any other way? Of course, there is. SQL provides an IDENTITY Function that can get the value of the identity column. Unfortunately, this function can only be used in the SELECT INTO statement, so we have to introduce a temporary table
Example:
USE pubs
SELECT IDENTITY(INT, 1, 1) AS Rank,au_lname,au_fname
INTO #tmp
FROM authors
SELECT * FROM #tmp
DROP TABLE #tmp
The performance and applicability of this method are stronger than the first method, but the disadvantage is that it must be completed through several SQL statements.
So if possible, it is generally recommended to complete this operation on the client
Thanks for your read and any advise.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631153.htmlTechArticleThere is often such a demand. I need to add a column of numbers similar to Identity to the query results. Although in It is not difficult to implement in Client programming, but sometimes I want to keep the existing Cl...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn