Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PK, FK Constraints design

Tags:

sql

oracle11g

I have the following tables structure.

TABLE1
SALARY_DETAILS(N_EMP_ID, D_MONTH ...)
N_EMP_ID NUMBER
D_MONTH DATE

PRIMARY KEY being composite: N_EMP_ID,D_MONTH

TABLE 2
INCOME_TAX(N_EMP_ID,D_YEAR,N_TAX...)

I want N_EMP_ID in TABLE2 to be a FOREIGN KEY on TABLE1(N_EMP_ID). Now this gives the following error:-

error

I understand the table being referred to has PK on both N_EMP_ID and D_MONTH. Obviously I shouldn't then do the below.

ALTER TABLE income_tax ADD FOREIGN KEY (person_id) REFERENCES salary_details(V_EMP_ID,D_MONTH);
  • Question 1: What is the right way/design to fix this?
  • Question 2: Can I have both PK and FK constraints on the same column: INCOME_TAX(V_EMP_ID)?

Thanks for your inputs.

Here is the Create table statement.

CREATE TABLE "ANKUR"."SALARY_DETAILS" 
   (    
    "V_EMP_NAME" VARCHAR2(30 BYTE), 
    "D_MONTH" DATE NOT NULL ENABLE, 
    "V_EMP_ID" VARCHAR2(10 BYTE), 
    "N_NET_PAY" NUMBER(10,2), 
    "N_TOT_EARNINGS" NUMBER(10,2), 
    "N_TOT_DED" NUMBER(10,2), 
    "N_BAS_SAL" NUMBER(10,2), 
    "N_FDA" NUMBER(10,2), 
    "N_HRA" NUMBER(10,2), 
    "N_MED_ALLW" NUMBER(10,2), 
    "N_TRANS_ALLW" NUMBER(10,2), 
    "N_LTA" NUMBER(10,2), 
    "N_BON_EXGRA_ADV" NUMBER(10,2), 
    "N_ANN_BON_EXGRA" NUMBER(10,2), 
    "N_PERF_BON" NUMBER(10,2), 
    "N_LWF" NUMBER(10,2), 
    "N_INCM_TAX" NUMBER(10,2), 
    "N_INFY_WELTRUST" NUMBER(10,2), 
    "N_MLPL" NUMBER(10,2), 
    "N_LIB_DEDUC" NUMBER(10,2), 
    "N_PF" NUMBER(10,2), 
     CONSTRAINT "PK_PERSON" PRIMARY KEY ("V_EMP_ID", "D_MONTH")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS"  ENABLE
   ) SEGMENT CREATION IMMEDIATE 
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS" ;
like image 674
TL36 Avatar asked Dec 03 '25 01:12

TL36


1 Answers

EMPLOYEES should be a separate table that both SALARY_DETAILS and INCOME_TAX refer to. This way, you can eliminate redundancy and also fix your FK problems.

like image 192
Erich Kitzmueller Avatar answered Dec 04 '25 15:12

Erich Kitzmueller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!