HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

nest SELECT in INSERT

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
nestselectinsert

Problem

I'm trying to do something like:

INSERT INTO stories 
   (vid, ip, body, timestamp) 
VALUES (
   (SELECT vid+1 FROM stories ORDER BY vid DESC LIMIT 1), 
   INET_ATON('127.0.0.1'), 
   'test', 
   NOW()
)


but I'm having a problem figuring out how to nest a SELECT statement's returned data into an INSERT statement. I need to figure out how to get the highest existing vid and increment it by 1.

Any ideas?

Solution

use an explicit SELECT, not nested

INSERT INTO stories 
   (vid, ip, body, timestamp) 
SELECT
   COALESCE(MAX(vid),0)+1,    --max always returns one row if no group by
   INET_ATON('127.0.0.1'), 
   'test', 
   NOW()
FROM stories
ORDER BY vid DESC LIMIT 1

Code Snippets

INSERT INTO stories 
   (vid, ip, body, timestamp) 
SELECT
   COALESCE(MAX(vid),0)+1,    --max always returns one row if no group by
   INET_ATON('127.0.0.1'), 
   'test', 
   NOW()
FROM stories
ORDER BY vid DESC LIMIT 1

Context

StackExchange Database Administrators Q#1817, answer score: 6

Revisions (0)

No revisions yet.