【问题标题】:MySQL insert into table with values and where [duplicate]MySQL插入带有值和位置的表[重复]
【发布时间】:2016-01-21 12:17:03
【问题描述】:

我有两个表 event 和 guest 以及一个 eventGuest 表,它将它们连接在一起并包含有关来宾的一些信息(例如他们是否参加等),并且我试图插入 eventGuest 表而不创建类似的重复类型:

insert into eventGuest(eventID, GuestID, attended) 
    values(iEventID, iGuestID, bAttended) 
where (select count(*) from eventGuest where eventID = iEventID and guestID = iGuestID) = 0

【问题讨论】:

  • 好的,谢谢分享。成功了吗?
  • 不,MySQL 不喜欢 where 的语法
  • 链接有效,但我需要在临时表中为 ID (巧合)相同时的列设置别名

标签: mysql


【解决方案1】:

将一个表数据复制到另一个:-

INSERT INTO TARGET_TABLE (`col1`,`col2`) SELECT `col1`,`col2` FROM SOURCE_TABLE;

【讨论】:

    【解决方案2】:

    如果你想将一个表中的值插入到另一个表中,你应该使用INSERT INTO ... SELECT

    INSERT INTO eventGuest(eventID, GuestID, attended) 
    SELECT iEventID, iGuestID, bAttended
    FROM Anothertable t
    where NOT EXIST(select 1 
                    from eventGuest e
                    where e.eventID = t.iEventID 
                      and e.guestID = t.iGuestID);
    

    或者,如果您想在eventidiGuestid 的值不存在的情况下插入到同一个表中,您可以这样做:

    INSERT INTO eventGuest(eventID, GuestID, attended)
    SELECT * 
    FROM ( SELECT 'eventid', 'guestid', 'somevalue' ) AS t
    WHERE NOT EXISTS (
        SELECT 1 FROM eventGuest e
               WHERE e.eventID ='eventid'
               and e.guestID = 'guestid'
    ) LIMIT 1;
    

    【讨论】:

      【解决方案3】:

      请在 eventGuest 表中为 eventid 和 guestid 添加唯一约束,并使用 INSERT IGNORE 或 REPLACE 命令插入新数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-02
        • 1970-01-01
        • 2022-12-07
        • 1970-01-01
        • 2012-03-25
        • 2017-04-24
        相关资源
        最近更新 更多