Insert multiple rows into two tables using autoincrement Mysql - mysql

I am trying to insert multiple rows into two tables connected by a foreign key that is autoincrement. I can't seem to find a good solution.
Tables:
eav_attribute_option
option_id (PK, Autoincrement)
attribute_id
sort_order
eav_attribute_option_value
value_id (PK, Autoincrement)
option_id (FK)
store_id
value
I want to do this:
insert into eav_attribute_option(attribute_id) values(100,101,102,103,...);
insert into eav_attribute_option_value(option_id,store_id,value) values
(1,0,"English"),(1,1,"German"),(2,0,"English1"),(2,1,"German2")
What would be the best approach to this, I can't seem to find a good one. :
Get next autoincrement then insert with it (need to lock table between)
Insert first part, then retreive PK values, build second part and insert (data incomplete for some time, what happens on error in second part?)
Some way to insert with join if it's possible?
Edit:
Just to clarify, I am looking to use the least amount of queries possible. I know I can do last inserted id, but I don't want to kill the server with thousands of inserts.

You can try something like this:
insert into eav_attribute_option (attribute_id) values(100);
insert into eav_attribute_option_value (option_id, store_id, value)
values (LAST_INSERT_ID(), 0, "English");
But you will need to insert the rows one by one. Consider doing a loop in your application.

$count = count('Count post value'); // $_POST value count
for($a=0;$a<$count;$a++)
{
$insert = 'insert into eav_attribute_option(attribute_id,sort_order) values (value1,value2)';
mysql_query($insert);
$insert_id = mysql_insert_id();
$insert2 = 'insert into eav_attribute_option_value(option_id,store_id,value) values
($insert_id,0,"English")';
mysql_query($insert2);
}

Related

Insert foreign key into table

I have two tables.
basically i want to insert an id and a string into a table
However, id is a foreign key to another table in which customerId is the primary key
Furthermore my parent table has name
What i have, is name and the stringthat i get from a web ui. However, since i dont have the id that match the customerid of name in the parent table, i don't know how to insert it.
i got this so far, which by the way is my silly attempt to work my human logic around this issue:
INSERT INTO `PostDb`(`Offer`)
VALUES ("String") AND PostDb.id
WHERE CustomerDb.id = PostDb.id AND CustomerDb.name = "MyNameThatIHave"
What would work though. is that i do the following:
SELECT PostDb.id
FROM `PostDb` JOIN CustomerDb
WHERE `CustomerId` = CustomerDb.id AND CustomerDb.name = "MyNameThatIHave"
And then use the id that i get in a new insert command like this:
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
VALUES ("THE ID I GOT BEFORE","STRING")
Basically i want to achieve in ONE query, what the two before stated queries does
You can use SELECT to get values for insert:
INSERT INTO `PostDb`(`Offer`, customerid)
SELECT 'Whatever', id FROM customerdb
WHERE name = 'MyNameThatIHave'
Have you tried LAST_INSERT_ID() function which gives you the last inserted ID PK provided that ID is an auto_increment column.
Once you get that, then you can insert in your child table in your FK column along with the rest attributes.
In that case, use a INSERT INTO .. SELECT FROM construct like
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
SELECT PostDb.`CustomerId`, 'Some Value'
FROM `PostDb` JOIN CustomerDb
ON `PostDb`.`CustomerId` = CustomerDb.id
WHERE CustomerDb.name = "MyNameThatIHave";

how to use primary key as custId number in second table

I have two tables, the first has an auto incrementing ID number, I want to use that as custId in the second table.
I am using an insert into the first table with all the basic info, name, address etc. Then in the second table only 3 things, custId, stocknum, and location. How can I write to these two tables kinda of simultaneously since stockNum may have several values, but always attached to one custId. I hope this makes sense even without putting code in here.
You can't insert into multiple tables at the same time. You have two options. You either do two inserts
INSERT INTO table1 (col1, col2) VALUES ('value1',value2);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO table2 (cust_id, stocknum, location) VALUES (LAST_INSERT_ID(), 'value3', 'value4')
Or you can use a post-insert trigger
CREATE TRIGGER table2_auto AFTER INSERT ON `table1`
FOR EACH ROW
BEGIN
INSERT INTO table2 (cust_id, stocknum, location) VALUES (NEW.id, value3, 'value4')
END
Hope this helps.
After inserting in the first table, The identity field or Auto increment field generate an ID
Get this id Refer Here(LAST_INSERT_ID() MySQL)
Then use this id to store value in the other table

MySQL inserting ID into multiple Rows

i got the following insert-command:
INSERT INTO PERSON ('Name','Age','Filename') VALUES ('Max',12,'Max_ID_.pdf');
i want to insert instead of 'Max_ID_.pdf' the string concartenated with the inserted id for this row. e.g.:
ID|Name|Age|Filename
2 |Max |12 |Max_2_.pdf
You can insert your row first, and than update it with the last inserted id:
INSERT INTO PERSON ('Name','Age','Filename') VALUES ('Max',12,'xxx');
UPDATE PERSON Filename=CONCAT(LAST_INSERT_ID(),'.pdf') where id = LAST_INSERT_ID()
There is also a way to do it in one statement, maybe a little more complex, and maybe will not work on every system, e.g. if you use innodb or transactions:
INSERT INTO PERSON SET Filename = CONCAT((SELECT auto_increment FROM
information_schema.tables WHERE table_name='PERSON'), '.pdf'),
Name = 'Max', Age = '12'

MySql Insert to multiple tables based on the ID generated in the first table

I have three tables in my database. A users table, StoreA and StoreB
StoreA and StoreB both have a unique key which is the user ID value.
What I want is; When I create a user and insert them into the database, how can I Insert a row into the other two tables without too many additional queries.
I figure I can do this by inserting the user in one query,
then in another return the newly created user ID,
then in another, using said ID, create rows in StoreA and StoreB
Can I cut out the middle query?
Can I cut out the middle query?
YES
START TRANSACTION;
INSERT INTO user (id, name, other)
VALUES (null, 'John','rest of data');
INSERT INTO storeA (id, user_id, other)
VALUES (null, #user_id:= LAST_INSERT_ID(), 'rest of data');
INSERT INTO storeB (id, user_id, other)
VALUES (null, #user_id, 'rest of data');
COMMIT;
See: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
It's a good idea to do this in a transaction, you you're not stuck with just a user with no other data if something goes wrong.
It's not a DB requirement though.
Yes - there should be a function available to get the last inserted ID (assuming it's an autoincrement field) without another query. In PHP, it's mysql_insert_id(). Just call that after the first query.
YES
Q1: insert into table1 values (...);
Q2: insert into table2 values (last_insert_id(), ...);
last_insert_id is the default mysql build-in function
Most of the mysql libraries in various programming language did support return last insert id.
But You did not mention what sort of language you are using to connect to mysql.,
so cannot provide any example
I just wanted to share a php solution.
If you're using mysqli, first execute your insert query.
Then do
$db_id = $this->db->insert_id;
Why don't you use their username as the primary key instead of creating an arbitrary user_id field thats auto incremented? Their user names are unique, right?

Is this a Efficient way to query relational tables on MySQL?

I'm dealing with a relational table and I've been wondering if there's a way to lower the number of queries I need to make when inserting data to the tables..
Here are the queries I currently use:
I insert the "main" values.
INSERT INTO products
(title, description, status, url)
VALUES
('some title', 'description of doom', 1, 'some-title');
We make it insert the value only if it doesn't exist already.
INSERT IGNORE INTO values
(value)
VALUES
('example value');
Since I'm not sure if the query was actually inserted, I get the id..
SELECT id
FROM
values
WHERE
value = 'example value';
Where "?" is the ID I got from the last query.
INSERT INTO link
( id_product, id_catalog, id_value )
VALUES
( 33, 1, ? );
This means that each extra value I need to add will cost 3 queries. So my question is: Is there a more efficient way to do this?
You can do this to at least drop one of the queries:
INSERT INTO link
( id_product, id_catalog, id_value )
VALUES
( 33, 1, (SELECT id
FROM values
WHERE value = 'example value') );
I basically am replacing the '?' with a sub select of the second query to get the id.
"Is there a more efficient way to do this?"
No. Not really. Creating three things takes three inserts.
You should be able to tell whether the insert succeeded with the ROW___COUNT() function from inside MySQL. If calling from another language (e.g. PHP), the mysql_query or equivalent function will return the row count.
You could use an INSERT INTO ... ON DUPLICATE KEY UPDATE statement.
This does, however, require that the primary key be one of the values for the insert, so it doesn't work on tables with an auto-increment.