how to use primary key as custId number in second table - mysql

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

Related

Insert multiple rows into two tables using autoincrement 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);
}

MySQL - Trigger that will automatic insert on other table

How can I create a trigger that will insert data into another table.
For example: I have a department table and a course table and the course table has a foreign key named department_id.
I insert CICCT into the course table but there is no CICCT in the department table.
My goal is to make the trigger add the value in the department table. How can I do this?
I tried this, is this correct?
CREATE TRIGGER department_insert BEFORE INSERT
ON course
FOR EACH row
begin
INSERT INTO department
(department_id,
description)
VALUES (new.id_dep,
NULL);
end;
Another question in the same subject, what do I need to do in order reduce the room capacity by one when a student enrolls?
Your trigger might look like this
CREATE TRIGGER department_insert
BEFORE INSERT ON course
FOR EACH ROW
INSERT IGNORE INTO department (department_id, description)
VALUES (NEW.id_dep, NULL);
Note:
to access column values of a row being inserted you have to use the NEW keyword
NEW.id_dep
^^^
use IGNORE clause in INSERT to ignore department_id values if they already exist in department table. It allows to greatly streamline your code.
Here is SQLFiddle demo
Make a separate post for your second question and specify table schemas

Adding only one value to the table in sql

I have a table named student which consists of (rollno, name, sem, branch)
If I want to INSERT only one value (i.e only name has to be entered) what is the query?
To insert values into specific columns, you first have to specify which columns you want to populate. The query would look like this:
INSERT INTO your_table_name (your_column_name)
VALUES (the_value);
To insert values into more than one column, separate the column names with a comma and insert the values in the same order you added the column names:
INSERT INTO your_table_name (your_column_name_01, your_column_name_02)
VALUES (the_value_01, the_value_02);
If you are unsure, have a look at W3Schools.com. They usually have explanations with examples.
insert into student(name) values("The name you wan to insert");
Be careful not to forget to insert the primary key.
First, if the table is all empty, just wanna make the column 'name' with values, it is easy to use INSERT INTO. https://www.w3schools.com/sql/sql_insert.asp.
`INSERT INTO TABLE_NAME (COLUMN_NAME) VALUES ("the values")`
Second, if the table is already with some values inside, and only wanna insert some values for one column, use UPDATE. https://www.w3schools.com/sql/sql_update.asp
UPDATE table_name SET column1 = value1 WHERE condition;
insert into student (name)
select 'some name'
or
insert into student (name)
values ('some name')
Following works if other columns accept null or do have default value:
INSERT INTO Student (name) VALUES('Jack');
Further details can be found from the Reference Manual:: 13.2.5 INSERT Syntax.
Execute this query, if you want the rest of columns as "#", do insert # inside the single quote which is left blank in query.
Also, there is no need of defining column name in the query.
insert into student values('','your name','','');
Thanks...

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.

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?