Created
July 12, 2016 15:25
-
-
Save PieterScheffers/3817b8d3f759a20a03c1483f5a0b8937 to your computer and use it in GitHub Desktop.
MySQL insert with subselect to insert a incrementing value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://stackoverflow.com/questions/10644149/insert-into-with-subquery-mysql | |
# Use a SELECT instead of VALUES | |
# Then give static values an alias | |
# Add a new row | |
# value for position should be the highest position in group + 1 | |
INSERT INTO some_table (group_id, name, position) | |
SELECT | |
2 as group_id, | |
'bert' as name , | |
(COALESCE(MAX(position), 0) + 1) as position | |
FROM some_table WHERE group_id = 2 | |
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice) | |
SELECT | |
/* Literal number values with column aliases */ | |
1 AS item_code, | |
2 AS invoice_code, | |
item_costprice | |
FROM qa_items | |
WHERE item_code = 1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment