Have column auto assigned through query - mysql

Essentially I want a column to give itself a value based off a value from another table when it gets inserted.
version_numbers (table) (id, ...): 1, 2, 3, 4, 5, 6
application_debug (table) (debug_id, ver_id ...)
On insertion, debug_id is set by the auto increment, but I would also like ver_id to be set with a query like this ver_id = SELECT MAX(id) FROM Version_Numbers
In this example, when inserting into application_debug I would like ver_id to be populated with the greatest id stored in version_numbers. I'm aware this can be done in multiple statements, but was wondering if there was a way to make the default values of a column be evaluated through a query on insertion.

Hi you can use select from as below:
insert into application_debug(ver_id) select max(id) from version_numbers;
If you want to insert any static values into application_debug which are not from verions_numbers, then you can write the query as below:
insert into application_debug(ver_id,col2) select max(id),'val2' from version_numbers;

Related

sql to inset into a table with select query from table having multiple rows

Im trying to figure out the right way to write sql to insert values from a table, where I need to pick Ids from anotehr table.
eg:
INSERT INTO `ts`.`priorityraw`
(`clientid`,`priorityid`,`typeid`)
VALUES
('AA',1,202),
('AA',1,203),
('AA',1,206),
('AA',1,210),
('AA',1,213);
Here clientId and priority is constant. typeid i need to pick from another table.
How can i modify above query to the following format? it gives issue with
as
syntx
INSERT INTO `ts`.`priorityraw`
(`clientid`,`priorityid`,`typeid`)
SELECT 'as01' AS `clientid`, '1' AS `priorityid`,
  id AS `typeid`
FROM
    ts.types
ORDER BY
   id;
INSERT INTO `ts`.`priorityraw`
(`clientid`,`priorityid`,`typeid`)
SELECT 'as01', 1,
id
FROM
ts.types
ORDER BY
id;

get the last ID after insert in mysql

how can i get the ID of the last insert statement
im using trigger to create a ID for every record
INSERT INTO table1_seqdocument VALUES (NULL);
SET NEW.tracknum = CONCAT('DOC', LPAD(LAST_INSERT_ID(), 3, '0'));
and i need that ID for other table
this is this my insert statement
INSERT INTO tble_transaction
(
tracknum
,signatoryid
,signed
,status
,signatorylevel
)
VALUES
(?,?,?,?,? )
what i want is to retrieve the ID and use it for another insert statement but using other table. is it possible? thank you
You can use ##identity
SELECT ##IDENTITY AS [##IDENTITY];
LAST_INSERT_ID() can only tell you the ID of the most recently auto-generated ID for that entire database connection, not for each individual table, which is also why the query should only read SELECT LAST_INSERT_ID() - without specifying a table. As soon as you fire off another INSERT query on that connection, it gets overwritten. If you want the generated ID when you insert to some table, you must run SELECT LAST_INSERT_ID() immediately after doing that (or use some API function which does this for you).
If you want the newest ID currently in an arbitrary table, you have to do a SELECT MAX(id) on that table, where id is the name of your ID column. However, this is not necessarily the most recently generated ID, in case that row has been deleted, nor is it necessarily one generated from your connection, in case another connection manages to perform an INSERT between your own INSERT and your selection of the ID.
(For the record, your query actually returns N rows containing the most recently generated ID on that database connection, where N is the number of rows in table1.)

How to insert a value from a select statement into a table along with a hardcoded value

I have a table called ROLES with ROLEID and ROLEDESC as the columns.
I am trying to get the max ROLEID from ROLES table and store it in another table along with a hardcoded value say 'NEWROLEDESC'
The new table(viz. 'DROLES') structure is: DID and DROLEDESC where DROLEDESC is to be populate with a hardcoded value and DID is to populated with a value from the select statement : SELECT MAX(ROLEID)+1 as maxroleid FROM ROLES
I have tried :
insert into DROLES(DID) SELECT MAX(ROLEID)+1 FROM ROLES
now,the above inserts the max ID in the DID, but when I try
insert into DROLES(DID,DROLEDESC)
values ((SELECT MAX(ROLEID)+1 FROM ROLES),'NEWROLEDESC')
It doesn't work.Ofcourse the SQL grammer is not correct. Is there any way to achieve it/The correct SQL Syntax?
NOTE: I am just writing this as an experiment. I know AUTO increment would do the trick.Anything apart from that?
Reinventing AUTO_INCREMENT(MySQL)/SEQUENCE/IDENTITY(SQL Server) is not the best way to go and you may end up with incorrect values with concurent queries!
The INSERT ... SELECT syntax is:
INSERT INTO DROLES(DID, DROLEDESC)
SELECT MAX(ROLEID)+1, 'NEWROLEDESC'
FROM ROLES;
Keep in mind that if you insert multiple times to DROLES and ROLES is not chaning you will get the same value in DID column.

Trouble with MAX(col)+1 INSERT into same MySQL table

I need two id columns in the same table that create unique values upon insert. Since MySQL allows only one column to auto-increment, I need to do something like max(id)+1 for the other column.
Here's the SQL I expected to work:
INSERT INTO invoices (invoiceid)
VALUES ((SELECT MAX(invoiceid)+1 FROM invoices))
The select statement works independently, but within my INSERT, it's not allowed. I get the error : You can't specify target table 'invoices' for update in FROM clause
You want to use INSERT INTO .... SELECT FROM instead of INSERT INTO...VALUES():
INSERT INTO invoices (invoiceid)
SELECT MAX(invoiceid)+1
FROM invoices
My question for you would be why are you not use an AUTO INCREMENT field to generate the invoiceid value? That is what it is for, then you will not have to create this when inserting data.

INSERT INTO with SubQuery MySQL

I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));
I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1
How i can solve this?
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
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;
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.
Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side. The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....
As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
INSERT INTO table_a(col1, col2, col3)
SELECT
col1,
col2,
CURRENT_TIMESTAMP()
FROM table_B
WHERE b.col1 = a.col1;
If you need to transfer without adding new data, you can use NULL as a placeholder.
If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
NewString VARCHAR(50)
);
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');
-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
WITH OtherSelect AS (
SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
)
SELECT os.OtherID, ns.NewString
FROM OtherSelect os, NewStrings ns;
This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.