doulangtiao4508 2013-12-02 06:09
浏览 20

插入但忽略如果重复AND如果存在于另一个表中则设置不同的值

I'm trying my make an invitation system together with the Facebook PHP APK. What I basically want is when you have invited your friends, Facebook redirects back to your website with an array containing userIDs from friends that the user invited. I wish to loop through them and insert the invitations into a database. The looping and all is already under control but the database query isn't.

This is what my current query looks like:

SELECT `iID` FROM `invitations` WHERE `iSender` = 'SENDER' AND `iReceiver` = 'RECEIVER';

If that returns zero rows I process this query:

INSERT INTO `invitations` (`iSender`, `iReceiver`) VALUES ('SENDER', 'RECEIVER');

And then I check if they're already signed up to my website:

SELECT `uID` FROM `users` WHERE `uOAuthID` = 'RECEIVER';

If it returns more then 1 row I run the following and final query:

UPDATE `invitations` SET `iProcessed` = 1 WHERE `iReceiver` = 'RECEIVER';

So basically this is how the process is currently shaped:

  1. If the user hasn't already has been invited by the inviter we insert the invitation into the database.
  2. Then we check if the invited user already is signed up.
  3. If he is signed up we update the invitation and say that it already has been processed.

I guess there's a better and faster method to do this with just maybe 1 or 2 queries. I've tried using INSERT IGNORE and ON DUPLICATE but that just gave me errors and gave up.

I hope that you understand what I'm looking for. Thank you all for your time!

  • 写回答

1条回答 默认 最新

  • dtkf64283 2013-12-02 06:24
    关注

    There are to thing that suite your needs:

    INSERT ... ON DUPLICATE KEY UPDATE Syntax:

    If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect:

    INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

    INSERT IGNORE:

    If you use the IGNORE keyword, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error occurs.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。