【问题标题】:MySQL INSERT if record exists in another tableMySQL INSERT 如果记录存在于另一个表中
【发布时间】:2012-12-15 22:36:14
【问题描述】:

我想保留一个查询的查询有点麻烦。基本上,我有两个表,用户和关系。用户有一个 ID,关系表有 user_a 和 user_b 字段,其中包含 users.id 值,将用户匹配为“user_a 跟随 user_b”。

现在我正在使用 Twitter API 来吸引 user_a 的关注者 (https://dev.twitter.com/docs/api/1/get/friends/ids) 但用户表中的人是参加活动的人, 不一定在 user_a 的朋友中。如果用户表中存在 user_b,我需要在关系表中执行 INSERT。

这是我目前所拥有的!

$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
    }
} 

【问题讨论】:

  • 可能带有触发器,直接在 MySQL 级别。我不记得确切的自定义触发器允许什么级别...
  • 我想你在找:$itll->be()->reet();

标签: php mysql codeigniter insert


【解决方案1】:

构建一个 select 语句,如果用户条目存在,则返回您要添加的行。然后执行 INSERT INTO user_a SELECT YOUR_STATEMENT;

例如。 INSERT INTO user_a SELECT uid, "value1", 2, "some other string" FROM user_b WHERE uid=$friend;

【讨论】:

  • 谢谢,用INSERT INTO relationships (user_a,user_b) VALUES ('43849096', (SELECT id FROM attendees WHERE id=2946339244));解决了
  • 如果 user_b 没有匹配的条目,则返回 null,对吗?从您的问题来看,在这种情况下应该发生什么并不太清楚 - 我的陈述根本没有插入任何内容。
猜你喜欢
  • 1970-01-01
  • 2016-03-09
  • 2014-02-21
  • 2017-10-21
  • 2019-12-03
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 2020-05-11
相关资源
最近更新 更多