简体   繁体   English

SQL“选择最大”查询

[英]sql 'select max' query

I have a table with name "table_name" approximately like this 我有一个名为“ table_name”的表,大致像这样

+----+-----------+
| ID | title     |
| 1  | title 1   |
| 2  | title 2   |
| ...| ......... |
| ...| ......... |
| n  | title n   |
+----+-----------+.

And I need a query that returns this result 我需要一个返回此结果的查询

+------+-----------+
| n+1  | title 1   |
| n+1  | title 2   |
| ...  | ......... |
| ...  | ......... |
| n+1  | title n   |
+------+-----------+

(n+1 is select max(ID) from table_name) (n + 1是从table_name中选择max(ID))

how can I do that? 我怎样才能做到这一点?

Simply add a sub-query to the select list: 只需将一个子查询添加到选择列表中:

select (select max(ID) + 1 from tablename), title
from tablename

Window function 视窗功能

SELECT MAX(ID) OVER() + 1, title
FROM table_name

You can select this max ID to a variable, and then simply use it in your select: 您可以选择此最大ID作为变量,然后只需在选择中使用它即可:

DECLARE @maxId INT = (SELECT MAX(ID) FROM [dbo].[table1]);
SELECT @maxId, t.title, t.column2, t.column3 ... from [dbo].[table2] t

For Mysql 对于MySQL

select (1+max(ID)) as ID ,title
from table_name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM