简体   繁体   中英

MySQL INSERT if record exists in another table

having a little trouble with a query that I'd like to keep to just one query. Basically, I have two tables, users, and relationships. Users have an ID, the relationships table has user_a and user_b fields which contain users.id values, which matches users up as 'user_a follows user_b'.

Now I'm hitting the Twitter API to pull in user_a's followers (https://dev.twitter.com/docs/api/1/get/friends/ids) but people in the users table are people attending an event, and not necessarily in user_a's friends. I need to execute an INSERT in the relationships table if user_b exists in the users table.

Here's what I have so far!

$json = file_get_contents('https://api.twitter.com/1/friends/ids.json?cursor=-1&user_id=' . $this->_attendee->id);
$response = json_decode($json);
if($response->ids){
    foreach($response->ids as $friend){
        // query goes here
    }
} 

Build a select statement that returns the line you want to add exactly if the user entry exists. Then do INSERT INTO user_a SELECT YOUR_STATEMENT;

eg. INSERT INTO user_a SELECT uid, "value1", 2, "some other string" FROM user_b WHERE uid=$friend;

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