简体   繁体   中英

sql 'select max' query

I have a table with name "table_name" approximately like this

+----+-----------+
| 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)

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:

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

For Mysql

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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