简体   繁体   English

Oracle主键

[英]Oracle Primary Keys

Can you retriev a data record in oracle using only a portion of a composite primary key? 您可以仅使用组合主键的一部分来检索oracle中的数据记录吗?

example PK = Col1 + Col2 + Col3 示例PK = Col1 + Col2 + Col3

SELECT * 
  FROM table 
 WHERE Col1 = 'SomeDate'

You can pose that query, but it may not give you a single record unless you have a unique constraint on that column. 您可以提出该查询,但是除非您对该列具有唯一约束,否则它可能不会给您单条记录。 Though if you did, I'm not sure why you'd have the composite primary key. 尽管如果您这样做了,我不确定为什么会有复合主键。

Sure, but because it's a composite primary key, the query is not guaranteed to return a unique or empty result. 可以,但是由于它是复合主键,因此不能保证查询返回唯一或空的结果。 There is only guaranteed to be one unique combination of Col1+Col2+Col3; 仅保证存在Col1 + Col2 + Col3的唯一组合; there could thus be many columns with the same Col1, unless as Jody says you have specified an additional unique constraint on the one column. 因此,可能有许多列具有相同的Col1,除非乔迪(Jody)说过您在一个列上指定了其他唯一约束。

Yes, you can, and it's perfectly normal. 是的,可以,这完全正常。 You do it all the time with many-to-many tables. 您可以一直使用多对多表进行操作。

Here is a table with a composite primary key. 这是带有复合主键的表。

create table student_grade(
  course_id  varchar2(6) not null
 ,student_id varchar2(12) not null
 ,grade number            not null
 ,primary key(student_id, course_id)
);

...with some test data: ...带有一些测试数据:

COURSE STUDENT_ID        GRADE
------ ------------ ----------
DB101  Ronnis               70
DB102  Ronnis               70
DB103  Ronnis               70
DB101  user627093           70

Selecting on parts of the key would be completely normal. 选择部分键是完全正常的。

select *
  from student_grade
 where course_id = 'DB101';

COURSE STUDENT_ID        GRADE
------ ------------ ----------
DB101  Ronnis               70
DB101  user627093           70

However, note that you may never ever rely on a query on subset of a key to return a single record. 但是,请注意,您可能永远都不会依靠对键子集的查询来返回单个记录。 Sooner or later that query will return more than one row, and any logic that depends on it will break. 该查询迟早将返回多个行,并且依赖该查询的任何逻辑都会中断。

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

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