简体   繁体   English

SQL插入的唯一约束-ORACLE

[英]Unique constraint on SQL insert -ORACLE

Im running a script which would fire a select query and insert the results into a table. 我正在运行一个脚本,该脚本将触发选择查询并将结果插入到表中。

The select query is 选择查询是

select distinct a.child child_id, a.parent parent_id from cat a, par b WHERE a.child=b.catentid and b.catenttype_id='Product' and a.reltype_id='PRODUCT_ITEM'

and inserted into the table which is created as 并插入到创建为

create table TI_CAT_0 ( child_id NUMBER not null,parent_id NUMBER not null,PRIMARY KEY (child_id))

But I get a unique key constraint violation while running the script as "SYS_C00187123", and I checked this constraint name in all_constraints table and its on the TI_CAT_0 table only. 但是在以“ SYS_C00187123”运行脚本时遇到了唯一的键约束违规,并且我在all_constraints表中及其仅在TI_CAT_0表中检查了此约束名称。

Since I use the distinct command, I'm not sure why this violation is turning up. 由于我使用了distinct命令,因此我不确定为什么会出现这种冲突。 Its a Oracle DB. 它是一个Oracle数据库。

Assuming you are creating the TI_CAT_0 table from scratch and inserting records from your SELECT query, then you are either unintentionally inserting the same record more than once, or your initial query is returning multiple rows for each child_id . 假设您是从头开始创建TI_CAT_0表并从SELECT查询中插入记录,那么您无意地多次插入同child_id记录,或者您的初始查询为每个child_id返回多行。 If this is the case, you should run this query to see if your initial query is returning duplicate child_id values. 在这种情况下,您应该运行此查询以查看您的初始查询是否返回重复的child_id值。 Your query, as it is written, will return unique combinations of child_id and parent_id . 您编写的查询将返回child_idparent_id唯一组合。 You can check to see if multiple parents are associated with a single child with the following SQL: 您可以使用以下SQL检查多个父项是否与一个孩子相关联:

select 
    a.child, 
    count(a.parent) as parent_count
from 
    cat a
    join par b 
        on a.child = b.catentid 
where 
    b.catenttype_id='Product' 
    and a.reltype_id='PRODUCT_ITEM'
group by 
    a.child
having
    count(a.parent) > 1
order by 2 desc

The results (if any) will be all child_id values associated with multiple parent_id values. 结果(如果有)将是与多个parent_id值关联的所有child_id值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM