如果MySQL中的表失败,则插入记录

时间:2016-11-05 00:15:24

标签: mysql sql

这是我的问题:

INSERT INTO table (id, actions, date, comments, type, url, rating)
  SELECT * FROM (SELECT 'b7d54d99bf11', 'Information Exchanged', '1430463600', '', 'routine', 'http://example.com', '') AS tmp
    WHERE NOT EXISTS (SELECT url FROM table WHERE url = 'http://example.com')

我收到一条说Duplicate column name: ''的SQL错误,因为某些记录没有传递ratingcomments

如何避免错误?有没有更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:0)

您必须为列添加别名

>> [binarize(1:10);                % first input : integers from 1 to 10
    binarize(ones(1,10));          % second input: an array of ten '1's.
    binarize(bitxor(1, 1:10))]     % the xor operation between the two

ans =

0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 
0001 0001 0001 0001 0001 0001 0001 0001 0001 0001 
0000 0011 0010 0101 0100 0111 0110 1001 1000 1011 

答案 1 :(得分:0)

你根本不需要一个复杂的子查询:

INSERT INTO table (id, actions, date, comments, type, url, rating)
    SELECT 'b7d54d99bf11', 'Information Exchanged', '1430463600', '', 'routine', 'http://example.com', ''
    FROM (SELECT 1 as x) t
    WHERE NOT EXISTS (SELECT url FROM table WHERE url = 'http://example.com');

但是,更好的方法是让数据库进行检查。创建一个唯一约束/索引,然后在出现重复时将insert短语忽略更新:

alter table t add constraint unq_table_url unique(url);

insert into table (id, actions, date, comments, type, url, rating)
    select 'b7d54d99bf11', 'Information Exchanged', '1430463600', '', 'routine', 'http://example.com', ''
    on duplicate key update url = values(url);

这样做的好处是数据库将确保所有插入和更新的唯一性 - 并且每次都不需要检查执行数据库更改的代码。