如题:
在连接PostgreSQL后,如何用sql语句,实现保证某一列或某几列值不重复的插入。

解决方案 »

  1.   

    无法用SQL语句来保证。需要在表的定义上来实现,定义某列为 unique key 或者 primary key 就行了。
      

  2.   

    如果这几列是主键、唯一索引,可以,否则用TRIGGER解决
      

  3.   

    用unique作限制:
    iihero=#  create table t1(id int, col2 varchar(32), col3 int, unique(col2, col3));
    NOTICE:  CREATE TABLE / UNIQUE will create implicit index "t1_col2_key" for table "t1"
    CREATE TABLE
    iihero=# insert into t1 values(1, 'abc', 2);
    INSERT 0 1
    iihero=# insert into t1 values(2, 'abc', 2);
    ERROR:  duplicate key value violates unique constraint "t1_col2_key"
    DETAIL:  Key (col2, col3)=(abc, 2) already exists.
    STATEMENT:  insert into t1 values(2, 'abc', 2);
    ERROR:  duplicate key value violates unique constraint "t1_col2_key"
    DETAIL:  Key (col2, col3)=(abc, 2) already exists.
    iihero=#
      

  4.   


    如果定义某列为 unique key 或者 primary key后,插入时如果重复,应该会停止插入吧,因为我是用java执行查询后插入的,这样遇到重复时java程序也就停了,能不让java程序停止,而是跳过进行下一条插入吗?
      

  5.   

    你 java 中的插入语句是什么样?java 中的 try catch不就是专门用于这种情况的吗?
      

  6.   


    for (...)
    {
    try
    {
        insert...
    }
    catch (exception)
    {
        
    }
    }