简体   繁体   中英

Insert into“Table1” if a condition is met in “Table” 2 SQL

I posted a similar question to this which was about deleting, This one is about inserting.

Hello,

I'm making a little messaging application in PHP using a SQL database but have faced a small problem. I will try explain this as best as possible so here goes...

I have a table called "users" as following:

ID | Username | Password | Email 
-------------------------------------------
1  | Account1 | Pass 1   | email1@mail.com
2  | Account2 | Pass 2   | email2@mail.com

I then have another called "friends" as following:

UserID | FriendID
------------------
   1   |     2    

So what I need is a query that will insert data into the "friends" table if a condition is met in the "users" table

Example:

INSERT INTO 'friends' VALUES('$UserID', '$FriendID') IF (users.Password = $Password WHERE users.ID = $UserID)

I hope that was a good enough explanation but I'm finding this difficult to explain.

Thank for your help :)

This'd probably do

INSERT INTO friends (userID, friendID)
SELECT $userID, $friendID
FROM users
WHERE (users.password = $password) and (users.id = $userid)

If there where clause matches, you'd however many rows inserted as there are matches, and since you're selecting hardcoded values instead of fields, you'd just get those values inserted into the friends table.

尝试:

 INSERT INTO friends VALUES('$UserID', '$FriendID') where UserID in (Select ID from Users where users.Password = '$passoword' and users.ID = '$UserID')

You need to place the conditional logic within your application, and not within the SQL. Your application code itself should be responsible for determining whether or not the INSERT should be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM