dsd57259 2016-05-06 05:47
浏览 67
已采纳

插入使用相同的行(相同的主键)mysql php pdo

INSERT INTO courses1 (sys_id,name, location) 
SELECT *
FROM courses 
WHERE sys_id= $sysid

I have the two tables above and I want to insert in course1 what I have in course. But I get problem with sys_id because I get Integrity constraint violation: 1062 Duplicate entry '1' for key 'PRIMARY'' in so what I did is a added a column in courses1 named system_id but then I get another error saying column not match.

Tried

INSERT IGNORE INTO but ther result is not what I am expecting. The result I want is to have the data from course to course1 everytime I make a transaction. I want the data not to be overriden.

  1. What is the best solution for insert into when inserting same row(same primary key)?

UPDATE

My aim is to back-up the data (historical data). I want to record the data before editing it. basically what i am doing is inserting the data in another table before updating it

  • 写回答

2条回答 默认 最新

  • doushan15559 2016-05-06 06:07
    关注

    This question is a perfect example that demonstrates the fact that to give an answer, one have to understand the context of the question, not just write an automated post triggered by some keyword in the question.

    If you want a history table, it have to have a different structure from the main table. At least it should have a non-unique key for the id from the main table.

    So, make a history table of the same structure, but add a main_id field. That gives you a structure like

    id
    manin_id
    name
    location
    

    Then, to add a record into a history table,

    INSERT INTO courses_history SELECT NULL, * FROM courses  WHERE sys_id=?
    

    you may want also to add an index (non-unique) for the main_id field.

    This way it will allow to store multiple "replicas" of the same row from the main table.

    To get the last replica, you need a query like this:

    SELECT * FROM courses_history WHERE sys_id=? ORDER BY id desc
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀