douzhuo1858 2014-10-19 14:58
浏览 27
已采纳

SELECT和INSERT不选择

When I execute

INSERT INTO `survey`
  (`id`,`name`,`date_start`,`date_end`)
  values
  (:id,:name,NULL,DATE_ADD(NOW(), INTERVAL 1 MINUTE))
  on duplicate key UPDATE `name`=:name;
  SELECT coalesce(:id,LAST_INSERT_ID()) as 'id'

it inserts a new data fine, but doesn't select the id (which is needed later on in my php code)

I've tried this suggestion

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);

but this SQL throws errors (due to duplicate parameters)

SELECT ASCII(substr(`perm` FROM floor(:i/8)+1))&(1<<(:i%8))>0 as perm FROM `user` WHERE `id`=:id

I'm in a lose-lose situation, re-writing all my SQL code to not have duplicate parameters would be very messy, doing a separate select straight after inserting may not return the id I want. Any suggestions would be great

  • 写回答

2条回答 默认 最新

  • dongpang4470 2014-10-19 17:04
    关注

    You cannot run two queries at the same time, only one at the time.

    If you want to do the whole thing at once then create a stored procedure.

    Same goes for complex queries, when it gets complicated you want to have your logic in the database.

    Here is an example:

    DELIMITER //
     CREATE PROCEDURE sp_insert_survey(IN `p_id`, 
                                       IN `p_name`, 
                                       IN `p_date_start`, 
                                       IN `p_date_end`)
       BEGIN
       INSERT INTO `survey`(`id`,`name`,`date_start`,`date_end`)
       VALUES (p_id, p_name, p_date_start, p_date_end);
    
       SELECT `id`,`name`,`date_start`,`date_end` 
       FROM survey WHERE `id` =LAST_INSERT_ID();
       END //
     DELIMITER ;
    

    Call the sp from PDO:

    $stmt = $db->prepare('CALL sp_insert_survey(?, ?, ?, ?)');
    

    then fetch the data as a SELECT query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b