Can an auto-incremented value in MySQL be preserved? - mysql

How do I preserve the last_insert_id() into a specific record?
Here are my queries:
INSERT INTO student(student_name) VALUES ('ramgopal')`;
SELECT `last_insert_id()`;
INSERT INTO grades (student_id,grade) VALUES (last_insert_id(),'A');
INSERT INTO class (semester,day,time) VALUES ('spring 2015','tuesday','12');
SELECT last_insert_id();
insert INTO grades(class_id) VALUES (last_insert_id());
In grade table I got grade_id, class_id, student_id and grade records.
When I use the last_insert_id() again it is just inserting the latest id and the previous id is not inserting. So I would like to preserve the initial last_insert_id for further use.

Related

MySQL - Insert into a table and get the ID of this to insert into another table -- all in one query

I have a exercise_logs table with these columns:
user_id | exercise_name | mood_log_id | weight_log_id | stretch_log_id
I have three tables (mood_logs, weight_logs and stretch_logs) whose primary key is stored in the 3 last three respective columns in exercise_logs.
These are columns my mood_logs table:
id | mood_scale
So I want to create a new mood_logs entry and use the id from that and store that in exercise_log. But I want to do it all in one query.
Here's what I tried so far:
INSERT INTO `exercise_logs` (`exercise_name`, `user_id`, `mood_log_id`)
values('Breathing', 190, (INSERT INTO `mood_logs` (`mood_scale`)
values(9); LAST_INSERT_ID()))
But this does not work.
Is it possible to achieve this in one query?
Thank you so much.
You can try this
First query insert into mood_logs
INSERT INTO `mood_logs` (`mood_scale`)
values(9);
2nd Query insert into exercise_logs
INSERT INTO `exercise_logs` (`exercise_name`, `user_id`, `mood_log_id`)
values('Breathing', 190, (SELECT `mood_scale` FROM `mood_logs` WHERE `mood_scale` = 9))
You first need to INSERT a row into mood_logs.
As the latest inserted id is from the above statement.
You can use last_insert_id() directly within the second insert statement.
INSERT INTO `mood_logs` (`mood_scale`) values (9);
INSERT INTO `exercise_logs` (`exercise_name`, `user_id`, `mood_log_id`) values('Breathing', 190, last_insert_id());
This is assuming you're the only using the database. If someone else uses an INSERT statement before you can use the last_insert_id() then, the id MIGHT be equal to whatever id the latest insert statement.
Can also use variables to store the last_insert_id();
INSERT INTO `mood_logs` (`mood_scale`) values (9);
SET #arbitraryVariableName = last_insert_id();
INSERT INTO `exercise_logs` (`exercise_name`, `user_id`, `mood_log_id`) values('Breathing', 190, #arbitraryVariableName);

sql insert to table realted to another table and constant values

I have 2 SQL tables, table1 and table2.
table1 has two columns and I want to insert values to these columns.
one of the columns should get a static value and the other column should get a value that is a result of a query from table2.
If I wanted to insert the static data separately I would do:
INSERT INTO table1(login_id)
VALUES ('1234');
and if I wanted to insert the dynamic value separately I would do:
INSERT INTO table1(user_uuid)
SELECT users_uuid FROM table2 where first_name like 'ortal';
How can insert both values to table1 in one action?
If I try the first query I get:
11:20:45 INSERT INTO table1(login_id ,user_uuid) VALUES ('1234') Error Code: 1136. Column count doesn't match value count at row 1 0.000 sec
INSERT INTO `users`.`table1` (`login_id`) VALUES ('1234');
ERROR 1364: 1364: Field 'user_uuid' doesn't have a default value
You can add the constants to your select list and treat them a columns:
INSERT INTO table1(user_uuid, login_id)
SELECT users_uuid, '1234' FROM table2 WHERE first_name LIKE 'ortal';

MySQL DB Trigger Insert after cost linked to id

first Trigger I created.
I have two tables, student and cost.
If I insert a new student I want to automatically insert a cost row for this student in the table cost and insert the corresponding student id to the cost.
I donĀ“t know how I can link the student id to the cost...
CREATE TRIGGER `add_cost` AFTER INSERT ON `student` FOR EACH ROW INSERT INTO cost (amount) VALUES (2000)
Thanks everybody!!
In your insert statement please use just:
NEW.{primary_key}
from related table(in your case student). If your primary is id this should looks like:
NEW.id
NEW is created after row is inserted and contain all inserted values + PK after insert.
Finally your query should looks like below:
INSERT INTO cost (student_id, amount) VALUES (NEW.id, 2000)
You can find more info on http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html

Inserting data into table SQL server

If I have 2 tables and Table 1 has a primary key(userID) AutoIncrement and Table 2 has a foreign Key(userID) to Table 1's (userID)
When I insert a new row into Table 1 first row will have userID = 1
Then if I insert again, userID = 2.
So how do I go about keeping Table 2's userID the same when inserting in Table 1. For instance, in Table 2, I am adding the password into another table.
My question is should I add an AUTOINCREMENT to Table 2(userID) and insert a new value into both tables when I create a user OR is there another way?
You have to manually insert data with correct id in Table2. There is no such built-in functionality in MySQL.
The algorithm is as follows:
Insert row in Table1.
Get Id of the new row.
Insert row with new id in Table2.
I think what you are looking for is this ... Assuming your ID is PK and AI
INSERT INTO yourTable (var1, var2 etc etc) VALUES ('val1', 'val2' etc etc);
SELECT LAST_INSERT_ID();
To further it ..
INSERT INTO yourTable (var1, var2 etc etc) VALUES ('val1', 'val2' etc etc);
SET #last_id = LAST_INSERT_ID();
INSERT INTO yourTable2 (id, var1, var2) VALUES (#last_id, 'blah', 'blah');

2 Dates from the same column in one SQL query

I'm trying to work out an average between of time between two dates in the same field.
Basically i've got a transaction date and an id for each transaction and a customer id for each transaction.
I need to get the time between the first transaction and the second transaction. I dont mind working out the average between the two in excel but I dont know how to pull two dates from the same field.
transaction.created_at of the first transaction minus transaction.created_at of the second transaction for each and every customer in the database. I can pull the date of a transaction like
select
customer.id,
transaction.created_at
count(transaction.id)
from transaction
having count(transaction.id) = 2
Thanks
Not sure if this will always be Having count(*) = 2? If so, I think you could just use min and max, no?
/*
create table dbo.Example (tran_id int,created_at datetime,cust_id int)
insert dbo.example values (1,'10/1/2012',900)
insert dbo.example values (2,'10/2/2012',901)
insert dbo.example values (3,'10/18/2012',590)
insert dbo.example values (4,'10/10/2012',676)
insert dbo.example values (5,'10/11/2012',123)
insert dbo.example values (6,'10/17/2012',456)
insert dbo.example values (7,'10/9/2012',901)
insert dbo.example values (8,'10/30/2012',900)
insert dbo.example values (9,'10/4/2012',456)
insert dbo.example values (10,'10/17/2012',676)
*/
select
cust_id,
max([created_at]) as [Last Date],
min([created_at]) as [First Date],
datediff(hh,min([created_at]) ,max([created_at])) as [Hours diff]
from example
group by cust_id
having count(*) = 2
order by cust_id
Try the following to retrieve particular customer transactions count:
Select
Customer.id,
count(transaction.id)
from transaction
where Customer.id = '10'
Here 10 specifies the customer id that has been searched by you. You have to pass this customer id as parameter in your created SP.