I have two tables one called users and another called profiles. Each of these tables has a column named user_id. What I want to do is when I insert a new user into the users table, I want to automatically copy over their new user_id in the users table to the profiles table. I don't want to use the UPDATE clause because then I would have to call that every time I add a new user. I thought that relations would achieve what I am trying to do so I made the user_id from profiles reference the user_id from users and it still doesn't update automatically. What should I do? And what is the point of relations in the first place if they don't update your columns automatically?
This is probably a design error. If rows in these two tables always exist with the same IDs, they should probably be a single table.
The foreign key you've created only guarantees that every row that exists in profiles must have the same ID as a row in users. It does not cause those rows to be created -- it just means that if you try to create a row with an ID that doesn't match, the database will throw an error.
That all being said, it's possible to create a trigger to do what you're describing:
CREATE TRIGGER user_insert_creates_profile
AFTER INSERT ON users
FOR EACH ROW
INSERT INTO profile (user_id) VALUES (NEW.user_id);
But it's probably better to reconsider your design, or to do the insert in your application. Triggers are best avoided.
Related
I just was wondering if is it possible to associate an user to the data inserted in a table.
For example:
I have a table Customers with columns customerID, name and address. Is there any method in MySql to know what user has inserted each row in the table or must I add a column userID in the table Customer to add the user in my SQL Insert statement?.
If I have only one table, it is not a proble to add the userID column. But when i have multiple tables, maybe it becomes a messy task.
Thanx in advance.
If you are trying to find out the user_id caused the insert then NO, there is no other way than you storing it explicitly likewise you already have thought of.
If there is multiple tables for which you want to store the same information; then you can probably have a separate table where you can have the user_id column and can use a AFTER INSERT TRIGGER to insert the user id in this table.
No, no such functionality is provided by MySQL. You'll have to add a column for user_id in your table(s) and insert the user id yourself.
I have two tables user and friends where users from user table can become friends.I have inserted 3 users into user table,now i want to make friends out of for example user_id = 1 and user_id = 2 but i don't know how to add this two id's in friends table.Photos of these two tables are attached.
... I don't really know what software you are using, but what you need is to declared a foreign key "UserId" column in your friend's table. Once that is done you can insert data in anyway possible by either using Mysql or a simple SQL insert:
INSERT INTO `friend`(UserId) VALUES (1)
I have a table 'project' that has attributes:name, UID(PK), section(distinguisher)... and 3 tables A,B,C based on section with specific properties of each section.i want to be able to enter data into project and the section specific data into A/B/C TABLE based on entry in section attribute of project table of that row. all tables have Foreign key with UID as UID_A, UID_B, UID_C...any ideas on how i can do it? all help appreciated as i am quite a novice...thanks! I am working with Mysql workbench.
Well, create a trigger on the table project:
CREATE TRIGGER `fill_abc` AFTER INSERT ON `project`
FOR EACH ROW BEGIN
INSERT INTO A <some specific data...>;
INSERT INTO B <some specific data...>;
INSERT INTO C <some specific data...>;
END;
Probably, you want to handle not only inserts into this table, but updates and deletes as well - it is nearly the same idea. See trigger definition here and examples here
I could have the wording 'wrong' here (new to mysql) but i hope i've explained what I'm trying to do well.
i have a table called submissions with 4 fields submitId, studentName, submitDate, status
status refers to whether they got admitted or not.
submitId is auto incremented
Now i wanted to create another table based on that, but only if the status is true, this new table would have the submitId, studentName, submitDate, plus additional fields.
this table would have a new auto increment studentId
how would i do that so it automatically updates any new entry to the first table on the second table, but not overwrite the additional content of table 2.
i thought of using a view, but u can't add new columns on the view, right?
do i have the logic wrong here or what are the options, could someone please point me in the right direction, thanks
You want to use a trigger. See:
http://dev.mysql.com/doc/refman/5.6/en/triggers.html
You can create the trigger so that when a row is inserted into submissions with status=true, it inserts a row into your new student table. It would look something like this:
delimiter //
CREATE TRIGGER sub_ins_check AFTER INSERT ON submissions
FOR EACH ROW
BEGIN
IF NEW.status = 1 THEN
INSERT INTO your_new_table (student_name, submit_date, submit_id) VALUES (NEW.student_name, NEW.submit_date, NEW.submit_id);
END IF;
END;//
delimiter ;
Then create another trigger so that when a row is updated in submissions, it updates the row with the same submit_id in your new table, like this:
delimiter //
CREATE TRIGGER sub_ins_check AFTER UPDATE ON submissions
FOR EACH ROW
BEGIN
IF NEW.status = 1 THEN
UPDATE your_new_table SET student_name = NEW.student_name, submit_date = NEW.submit_date, (etc..)) WHERE submit_id = NEW.submit_id;
END IF;
END;//
delimiter ;
I think your data model is wrong. Remember that student my have several submissions and there may be number of students with the same name. You must distinguish them.
Is there any reason you want to duplicate student data in both tables?
If you're new to SQL, read about table normalization first.
In you Student table you should store students data and in Submission table - guess what :)
The first thing you need to do is step back and consider the problem from the perspective of logical entities.
You've identified two entities that I can see - student and submission. "Student" is an obvious entity which you may choose NOT to store in your database, but it may be better that you do. "Submission" is a more obvious one, but what is not so obvious is what a "submission" actually is. Let's assume it is some sort of transaction.
You've mentioned a "second table" without a clear indication of its role in the solution. The best I could infer is that it is meant to be some sort of historical trail on activity against a submission. If true, then I could envision a physical schema sketched out as follows:
Student table. One row per student; contains information about a student (name, id, etc.). Primary key would probably be an auto-incremented number.
Submission table. One row per submission; includes a foreign key to the student table (referencing the primary key); has its own primary key, also an auto-incremented integer. Also has triggers defined for INSERT and UPDATE. INSERT trigger causes INSERT into submission_log table; UPDATE trigger also causes INSERT into submission_log table.
Submission_log table. One row per event against the submission table. Includes all the fields of submission plus its own primary key (submission's primary key is a foreign key here), and includes an indicator field for whether it represents an insert or update on submission.
The purpose of the above is not to supply a solution, or even the framework of a solution, but rather to get you to think in terms of the logical entities you want to model in your solution, and their relationships to each other. When you have a clear picture of the logical model, it will be much easier to determine what tables are required, what their roles are, and how they will be used and how they will relate to each other.
I have a webapp that currently stores all of a user's searches into a search_log table. I now want to create another table called results_log that stores all the results we supply to the user. The search_log table contains a primary key called id_search and the results log table has the foreign key id_search, and one other field id_result. The id_searched field is an auto_incrementing field in both tables.
In my web app I would do the inserts in this sequential order:
insert into search_log table
insert into result_log table
I am worried this may cause a race condition. If user A and user B both finish the webapp and reach this part of the code at about the same time, is it possible that the order would go:
User A -> Insert into search_log
User B -> Insert into search_log
User B -> Insert into result_log
User A -> Insert into result_log
Since both tables are auto_incrementing on the id_search field, I'm worried User A and User B will have their data swapped. I also thought about querying for the id_search, but it seems like a even worse solution.
My question is:
-Is there a way to fix this race condition?
-Would one solution be inserting into two tables with one SQL query? Is this possible?
If those tables are related, then you should include the auto increment ID with when inserting. After inserting into search_log, get the last insert ID, no lookup needed. Then include that in the result_log search as another field.
Never rely on auto increment IDs being the same in different tables.