search
Homephp教程php手册关于如何在查询结果中添加自动编号

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

Jun 13, 2016 am 10:05 AM
aboutInquireAdd toofresultserial numberautomaticneed

往往经常有这样的需求,我需要在查询的结果中添加一列类似于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.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor