Home> php教程> php手册> body text

关于如何在查询结果中添加自动编号

WBOY
Release: 2016-06-13 10:05:22
Original
1879 people have browsed it

往往经常有这样的需求,我需要在查询的结果中添加一列类似于Identity的数字,虽然在Client编程中并不难实现,但是有时我想留用现有的Class,不希望在Client side做额外的coding,那么就只有在Sql里面想办法了
首先介绍一种用一条SQL语句完成的办法,原理是在结果中查询大于等于该纪录的纪录条数,就可以得到它的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
不过呢,这种方法有它的局限性,第一是性能不好,第二是如果存在相同的纪录,那么Rank就会出现并列的情况,比如出现两个2,但是没有3了
有没有别的方法呢?当然有的,SQL提供了一个IDENTITY Function,可以得到标识列的值,不过可惜的很的是,这个函数只能用于SELECT INTO语句,所以我们只好引入一个临时表了
Example:
USE pubs
SELECT IDENTITY(INT, 1, 1) AS Rank,au_lname,au_fname
INTO #tmp
FROM authors
SELECT * FROM #tmp
DROP TABLE #tmp
这种方法的性能和适用性都比第一种方法要强,不过缺点是必须通过几条SQL语句才能完成。
所以如果可能的话,一般还是建议在客户端完成这一操作
Thanks for your read and any advise.

source:php.cn
Statement of this Website
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
Popular Recommendations
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!