update a table when new data is available in another table - mysql

I have two table:
Am using this query to populate my marks table with all 'id' in student table:
$module1= "insert into marks (stud_id,moduleID)
select sid, 1
from user_student
where sid not in (
select * from (
select distinct stud_id from marks where moduleID=1
) alias_name
)";
So i need to take all 'sid' from Table student and populate them into table marks my query above does all that. The problem am encountering is that every time i make a change to the data e.g column test1 , new record are inserted again.
If i populate the marks table manually, Can't i have a code that when new data is available in student table, the data is just updated in marks table...

I don't understand some points of your insert query, why insert sid in stud_id if there's a id in student table to relate them?
Maybe solve your problem the creation of a composed unique key to moduleID and stud_id and use a REPLACE in place of INSERT.
But the right way to do it is using a TRIGGER like:
DROP TRIGGER IF EXISTS `student_after_insert`;
CREATE TRIGGER `student_after_insert` AFTER INSERT ON `student`
FOR EACH ROW INSERT INTO marks (stud_id,moduleID)
SELECT NEW.`id`, `modules_table`.`id` FROM `modules_table`;
PS: I suppose you have a table of modules with name modules_table. Change it accordingly.

I haven't understand your question at the best, my tip is:
Make a unique constraint on marks table (up to you is the choice of best constraint rule).
Then use a trigger to make the right insert/update:
Something like that, (hope that syntax is right):
CREATE TRIGGER myTrigger
AFTER INSERT ON students
FOR EACH ROW
BEGIN
// check that insertion doesn't broke the constraint previously define, then
insert into marks (stud_id,moduleID) values (new.sid, 1);
END
Note: NEW is the row that you have as soon inserted/updated on students. Similar you have OLD metarow.

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";

MySQL workbench 6.2 auto-increment

The problem is I have class_id,faculty_id,course_id,semester,day and time records in class table. The class_id in this table is auto-incremented, faculty_id and course_id are also auto_incremented in there own respective tables.
My question is, when I insert values of semester, day and time I want the rest of the three ids(class_id,faculty_id and course_id) to be auto-incremented. I tried it with the help of triggers but it is not incrementing all the records together but it is incrementing one after the other.
Here are the queries used:
CREATE DEFINER=`root`#`localhost` TRIGGER classINSERT AFTER INSERT ON `faculty` FOR EACH ROW
begin insert into class(faculty_id) values(new.faculty_id);
end
CREATE DEFINER=`root`#`localhost` TRIGGER classINSERT2 AFTER INSERT ON `course` FOR EACH ROW
begin insert into class(course_id) values(new.course_id);
end
I guess, you are mis interpreting the word "auto-increment" and its function with your current needs. From your two triggers i see you are trying to insert a new record into the tbl_class table when a new faculty/course is created.
CREATE DEFINER=`root`#`localhost` TRIGGER classINSERT AFTER INSERT ON `faculty` FOR EACH ROW
begin
insert into class(faculty_id) values(new.faculty_id);
end
above code tells me after insert on tbl_faculty insert a new record in to the tbl_class with newly created faculty_id. There is no sign of course_id. of course it will show as blank/null if you don't set it.
the same applies for the other trigger.
I'm not sure if this thats is your intention but AFAIK this does not make any sense. The tbl_class should be created with existing faculty_id and course_id probably a drop-down-box in your form.
in case if you want to create new course or new faculty while creating a new class record. that is completely different question from what you are asking now. That would require a new form taking the new faculty name and perform an insert on the table and refresh the drop-down-box.

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

Trigger insert deleted row

Hello I have some difficulties with simple trigger in MSSQL 2008.
I want to insert deleted row to another table.
Here is my trigger code:
use databasex;
GO
CREATE TRIGGER DeleteEmployee
ON Employees
FOR DELETE
AS
BEGIN
INSERT INTO DeletedEmployees (Name, Surname, Function)
VALUES (deleted.Name, deleted.Surname, deleted.Function)
END
Employees table:
Name Surname Function ...
DeletedEmployees table:
Name Surname Function ...
I need somehow to specify that deleted columns are from deleted table, but how ?
I dont want to write subquery for every column.
How it being done ?
ps: is there any good tutorial on using triggers ? i believe i will need write more triggers in the future.
DELETED is a virtual table you select from (you may have deleted more than one row, so a single value is not enough)
Also, FUNCTION is a reserved word and needs to be escaped
CREATE TRIGGER DeleteEmployee
ON Employees
FOR DELETE
AS
BEGIN
INSERT INTO DeletedEmployees (Name, Surname, [Function])
SELECT Name, Surname, [Function] FROM deleted
END
An SQLfiddle to test with.

Duplicate record in mySQL

I have a mySQL db with duplicate records, as from the attached image.
I am asking for a query to delete all duplicate records based on date + time, for all tables (foreachtables) in db
Thanks
As far I could see, you dont have autoincrement primary key or foreign key.
If you dont have tables with foreign key or relation between, first you can list all your tables. After that, you can create a temporal "mirror" of one table (for eg, autogrill).
Then you can do a:
INSERT INTO TemporalTable
SELECT DISTINCT
or a
INSERT INTO TemporalTable
SELECT Id, Date, Time FROM autogrill GROUP BY Id, Date, Time HAVING COUNT(*) > 1
.
TRUNCATE or DELETE FROM
without where and then put again your data with
INSERT INTO autogrill
SELECT * FROM TemporalTable
BE AWARE if you have primary keys doing this.
How about you create and STORED PROCEDURE for this?
DELIMITER $$
CREATE PROCEDURE `DeleteDup`()
BEGIN
-- Drops the table.
DROP TABLE bad_temp;
-- Creates a temporary table for distincts record.
CREATE TABLE bad_temp(id INT, name VARCHAR(20));
-- Selects distinct record and inserts it on the temp table
INSERT INTO bad_temp(id,name) SELECT DISTINCT id,name FROM bad_table;
-- Delete All Entries from the table which contains duplicate
-- (you can add also condition on this)
DELETE FROM bad_table;
-- Selects all records from temp table and
-- inserts back in the orginal table
INSERT INTO bad_table(id,name) SELECT id,name FROM bad_temp;
-- Drops temporary table.
DROP TABLE bad_temp;
END$$
DELIMITER ;
Please change tablename and column name to your desired schema.
so when you finish creating your STORED PROCEDURE, you can use it like this:
CALL DeleteDup();
You can export your table using this request :
SELECT * FROM autogrill GROUP BY id
Then, empty your table, and import the export you made before. I don't know another easy way to erase duplicate entries using only a single request.
One easy way to do this is to copy all the distinct records into a new table or an export. Then delete all records in the original table and copy them back in.
Export NULL if table have autoincrement an for source use alias name, example :
INSERT INTO product
SELECT NULL,p.product_sku,
p.product_s_desc,
p.product_desc,
p.product_thumb_image,
p.product_full_image,
p.product_tech_data,
p.product_publish,
p.product_weight,
p.product_weight_uom,
p.product_length,
p.product_width,
p.product_height,
p.product_lwh_uom,
p.product_url,
p.product_in_stock,
p.product_available_date,
p.product_special,
p.create_date,
p.modify_date,
p.product_name,
p.attribute
FROM product AS p WHERE p.product_id=xxx;