Home > Back-end >  Reversing DELETE Query to an INSERT INTO query
Reversing DELETE Query to an INSERT INTO query

Time:10-14

For an assignment I have which includes a delete and add friend system (like Facebook), I've made a query that works by using two SQL tables, one which includes a friend_id, name and other information, and another which holds two friend_id columns, that show the relationship with the users and if they're friends.

User Table
| friend_id  | name       |
|:---------- |:----------:|
| 1          | John       |
| 2          | Peter      |
| 3          | Alex       |
| 4          | Nick       |
Friendship Table (myfriends)
| friend_id1 | friend_id2 |
|:---------- |:----------:|
| 1          | 3          |
| 2          | 4          |
| 3          | 1          |
| 4          | 2          |
 -------------------------

This example shows that users 1 and 3 are friends, and 2 and 4 are friends.

This is my current DELETE query, which follows as

DELETE FROM myfriends WHERE (friend_id1 = 1 AND friend_id2 = 3) OR (friend_id1 = 3 AND friend_id2 = 1);

I want to invert it so rather than it deleting, it will add the friendship pair

INSERT INTO myfriends VALUES (friend_id1 = 1 AND friend_id2 = 4) OR (friend_id1 = 4 AND friend_id2 = 1);

UPDATE: Made this change so far, is this right?

INSERT INTO `myfriends`(`friend_id1`, `friend_id2`) VALUES ('1' ,'4'),('4','1');

CodePudding user response:

I think this question might be about the INSERT syntax? In your case it would be:

INSERT INTO myfriends (friend_id1, friend_id2)
VALUES (1, 4), (4, 1);

See: INSERT

  • Related