Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 6 down vote accepted

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
share|improve this answer
    
that's a great solution! thank you. one more thing though - how do I return an integer 1 for vid value if table stories is empty? –  donkapone Mar 20 '11 at 19:41
    
@Donkapone ~ That sounds like "I have two different business cases, I should test for one of them to be valid, and then execute one of two different paths depending on that test result" doesn't it? How would you solve it? –  jcolebrand Mar 21 '11 at 19:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.