CREATED OR MODIFY A TABLE WHICH HAVE A COMBINED PRIMARY KEY, FORM FROM 3 OF THEIR ATTRIBUTES - sql

I'm trying to created a table, and give as a primary key, the 3 attributes, which it have.
The code is below:
CREATE TABLE compra
(
dni_cli VARCHAR2(50),
cod_prod NUMBER(10) NOT NULL,
cantidad NUMBER (10),
CONSTRAINT pk_compra PRIMARY KEY (dni_cli, cod_prod, cantidad);
CONSTRAINT pelicula_codigo_prod_fg FOREIGN KEY (cod_prod) REFERENCES producto(cod_prod),
CONSTRAINT pelicula_codigo_cli_fg FOREIGN KEY (dni_cli) REFERENCES cliente(dni)
);
I also tried to create the table first, and then, add the constraint in order to create the combined PRIMARY KEY with the alter table, but is doesn't work.
The code is this:
ALTER TABLE CONSTRAINT pk_compra PRIMARY KEY (dni_cli, cod_prod, cantidad);

If the primary key already exists you need to drop the key:
ALTER TABLE compra drop constraint pk_compra;
then add the key:
ALTER TABLE compra add constraint pk_compra primary key (city_id, buildtime, time);
If the primary key does not exist in the table then just use the second command line.
Also as #stickybit noted your table has an error. This is the code without an error:
CREATE TABLE compra (
dni_cli VARCHAR2(50),
cod_prod NUMBER(10) NOT NULL,
cantidad NUMBER (10),
CONSTRAINT pk_compra PRIMARY KEY (dni_cli,cod_prod,cantidad), --<<change here
CONSTRAINT pelicula_codigo_prod_fg FOREIGN KEY (cod_prod) REFERENCES producto(cod_prod),
CONSTRAINT pelicula_codigo_cli_fg FOREIGN KEY (dni_cli) REFERENCES cliente(dni));

Related

Make attribute primary and foreign key in sql

How can I make an attribute a primary key within a table but also as a foreign key which references another table using sql in sql developer?
I know how to make it an attribute as a foreign key and a primary separate but not as a primary key as well as a foreign key
That's perfectly normal. For example:
create table employee (
id number(6) primary key not null,
name varchar2(50)
);
create table employee_desk (
desk_id number(6) primary key not null, -- PK and FK!
location varchar2(20),
constraint fk1 foreign key (desk_id) references employee (id)
);
The column desk_id is the primary key of the table employee_desk, and also a foreign key that points to the table employee.
Below is the example of primary key with foreign key
create table animals (id integer primary key);
create table cats (
id integer primary key
, name varchar(100) not null
, constraint d_cats_animals_fk foreign key (id) references animals (id)
);

I have no idea why I get an error when putting the foreing keys in MariaDB

I have no idea why I get an error when putting the foreing keys in MariaDB
I drop the full database if it exists
drop database if exists proveedoresCarrito;
create database proveedoresCarrito;
use proveedoresCarrito;
And now I'm going to create the tables
CREATE TABLE INVENTARIO (
NUMPIEZA CHAR(16) NOT NULL,
NUMBIN SMALLINT NOT NULL,
CANTDISPONIBLE SMALLINT,
FECHARECUENTO DATE,
PERIODORECUEN SMALLINT,
CANTAJUSTE SMALLINT,
CARTREORD SMALLINT,
PUNTOREORD SMALLINT);
CREATE TABLE LINPED (
NUMPEDIDO SMALLINT NOT NULL,
NUMLINEA SMALLINT NOT NULL,
NUMPIEZA CHAR(16),
PRECIOCOMPRA INTEGER,
CANTPEDIDA SMALLINT,
FECHARECEP DATE,
CANTRECIBIDA SMALLINT);
CREATE TABLE PEDIDO (
NUMPEDIDO SMALLINT NOT NULL,
NUMVEND SMALLINT,
FECHA DATE);
CREATE TABLE PIEZA (
NUMPIEZA CHAR(16) NOT NULL,
NOMPIEZA CHAR(30),
PRECIOVENT INTEGER);
CREATE TABLE PRECIOSUM (
NUMPIEZA CHAR(16) NOT NULL,
NUMVEND SMALLINT NOT NULL,
PRECIOUNIT INTEGER,
DIASSUM SMALLINT,
DESCUENTO SMALLINT);
CREATE TABLE VENDEDOR (
NUMVEND SMALLINT NOT NULL,
NOMVEND CHAR(30),
NOMBRECOMER CHAR(30),
TELEFONO CHAR(15),
CALLE CHAR(30),
CIUDAD CHAR(20),
PROVINCIA CHAR(20),
COD_POSTAL CHAR(5));
create table usuarios(
nombre SMALLINT NOT NULL,
pass CHAR(15)
);
I Set up the primary keys
ALTER TABLE INVENTARIO ADD CONSTRAINT CP_INVENTARIO PRIMARY KEY (NUMBIN);
ALTER TABLE LINPED ADD CONSTRAINT CP_LINPED PRIMARY KEY (NUMPEDIDO, NUMLINEA);
ALTER TABLE PEDIDO ADD CONSTRAINT CP_PEDIDO PRIMARY KEY (NUMPEDIDO);
ALTER TABLE PIEZA ADD CONSTRAINT CP_PIEZA PRIMARY KEY (NUMPIEZA);
ALTER TABLE PRECIOSUM ADD CONSTRAINT CP_PRECIOSUM PRIMARY KEY (NUMPIEZA, NUMVEND);
ALTER TABLE VENDEDOR ADD CONSTRAINT CP_VENDEDOR PRIMARY KEY (NUMVEND);
AND FINALLY i set up the foreign keys
ALTER TABLE INVENTARIO ADD CONSTRAINT CP_INVENTARIO PRIMARY KEY (NUMBIN);
ALTER TABLE LINPED ADD CONSTRAINT CP_LINPED PRIMARY KEY (NUMPEDIDO, NUMLINEA);
ALTER TABLE PEDIDO ADD CONSTRAINT CP_PEDIDO PRIMARY KEY (NUMPEDIDO);
ALTER TABLE PIEZA ADD CONSTRAINT CP_PIEZA PRIMARY KEY (NUMPIEZA);
ALTER TABLE PRECIOSUM ADD CONSTRAINT CP_PRECIOSUM PRIMARY KEY (NUMPIEZA, NUMVEND);
ALTER TABLE VENDEDOR ADD CONSTRAINT CP_VENDEDOR PRIMARY KEY (NUMVEND);
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_NOMBRE FOREIGN KEY (nombre) REFERENCES VENDEDOR(NUMVEND);
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_PASS FOREIGN KEY (pass) REFERENCES VENDEDOR(TELEFONO);
However, all the foreign keys work correctly except for the last two
when i run the sql script i get this error:
Error de SQL (1822): Failed to add the foreign key constaint. Missing index for constraint 'CA_VENDEDOR_USUARIOS_PASS' in the referenced table 'vendedor'
if I drop the last two foreign keys the error disappears
Anyone can give me a solution?
Look closely at your "set up the foreign keys" code. It creates primary keys again (except the two last lines).
Table usuarios seems to have no primary key.
ALTER TABLE usuarios ADD CONSTRAINT CP_usuarios PRIMARY KEY (nombre);
Delete the first 6 lines and keep only these
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_NOMBRE
FOREIGN KEY (nombre)
REFERENCES VENDEDOR(NUMVEND);
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_PASS
FOREIGN KEY (pass)
REFERENCES VENDEDOR(TELEFONO);
Also (and this is what generates your error), you are trying to add a foreign key to a column VENDEDOR(TELEFONO) which is not a primary key nor has a UNIQUE constraint.
According to Microsoft:
A foreign key constraint does not have to be linked only to a primary key constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
See: Create Foreign Key Relationships
Add this before creating the foreign keys:
ALTER TABLE VENDEDOR ADD CONSTRAINT UX_telefono UNIQUE (TELEFONO);
A foreign key has to reference always a primary key.
For you to reference the table VENDEDOR you should use the columns that compose its PK. In this example, NUMVEND.
If you need any suggestions on what to do, i'd have to know what are your intentions on this DB structure.

Recursive relationship SQL error

I am pretty new to SQL and I have a problem. I want to make a recursive relationship (a table that relates to itself), but I get an error when I try to execute my code. It's working fine without the Coordinator_Office_ID foreign key.
The error is:
The number of columns in the foreign-key referencing list is not equal
to the number of columns in the referenced list.
Create table Logistican (
Office_ID Number(10) Constraint nb_office Not NULL,
Worker_ID Number(15) Constraint lg_worker not null,
Name_logistican Varchar(20),
Room Varchar(10) constraint log_room UNIQUE,
Coordinator_Office_ID Integer,
Primary key (Office_ID, Worker_ID),
Constraint work_id Foreign key (Worker_ID) References worker(worker_ID) on delete cascade,
Constraint lg_cord_id Foreign key (Coordinator_Office_ID) References Logistican(Office_ID)
);
Yes, that's cause you have defined composite primary key like Primary key (Office_ID, Worker_ID) and thus your FK should include both of them else it will result in PFD (partial functional dependency)
Add the constraint with alter table:
Create table Logistican (
Office_ID Number(10) Constraint nb_office Not NULL,
Worker_ID Number(15) Constraint lg_worker not null,
Name_logistican Varchar(20),
Room Varchar(10) constraint log_room UNIQUE,
Coordinator_Office_ID Integer,
Primary key (Office_ID, Worker_ID),
Constraint work_id Foreign key (Worker_ID) References worker(worker_ID) on delete cascade
);
alter table Logistican
add Constraint lg_cord_id
Foreign key (Coordinator_Office_ID, Worker_Id) References Logistican(Office_ID, Worker_Id);
The relationship needs all elements of the primary key to be valid. I'm not sure if it needs to be a separate statement in Oracle.

ORA-02270 Referencing a foreign key

I have 1st table:
CREATE TABLE HEAD (
Code int,
Name varchar(99),
HType char(1),
HDate date,
OpBal number(10),
CONSTRAINT pk_head PRIMARY KEY (Code, Name));
and 2nd table:
CREATE TABLE SUBHEAD (
HCode int,
SubCode int,
Name varchar(99),
SDate date,
OpBal number(10),
CONSTRAINT fk_subhead FOREIGN KEY (HCode) REFERENCES HEAD(Code),
CONSTRAINT pk_subhead PRIMARY KEY (Hcode, SubCode));
Now when I run the script, I get:
CONSTRAINT fk_subhead FOREIGN KEY (HCode) REFERENCES HEAD(Code),
ERROR at line 7:
ORA-02256: number of referencing columns must match referenced columns
I have been looking around trying to figure out what's wrong and I think it has something to do with parent table constraint but I am totally stumped on how to fix this.
Your problem is that your foreign key is not referencing the entire primary key from HEAD.
So you either need to change the foreign key (to include name in there) or change the primary key of HEAD to exclude name there.
So either change
CONSTRAINT pk_head PRIMARY KEY (Code, Name));
to
CONSTRAINT pk_head PRIMARY KEY (Code));
or change
CONSTRAINT fk_subhead FOREIGN KEY (HCode) REFERENCES HEAD(Code)
to
CONSTRAINT fk_subhead FOREIGN KEY (HCode, Name) REFERENCES HEAD(Code, Name)

Invalid FK and PK reference

Unable to create table as oracle shows ' no matching unique or primary key for this column-list' when I did label the primary key reference for the required table.
First table created successfully:
CREATE TABLE TEST
(
TESTno VARCHAR2(6) NOT NULL,
ExamNo VARCHAR2(6) NOT NULL,
TEST_Date DATE NOT NULL,
ACTUAL DATE,
PREDICTED Date,
CONSTRAINT TESTPKs PRIMARY KEY (TEST_Date, TESTno, ExamNo),
CONSTRAINT TTESTNO_Fk FOREIGN KEY (TESTno) REFERENCES TESTPAPER (Flightno)
CONSTRAINT TEXAMNo_FK FOREIGN KEY (ExamNo) REFERENCES Exam (ExamNo)
);
Here's the table i want to create and gives me error:
CREATE TABLE Assignment
(
TEST_Date DATE NOT NULL,
ExamNo VARCHAR2(6) NOT NULL,
TestNo VARCHAR2(6) NOT NULL,
Type VARCHAR2(20),
Hours_Spent Decimal(4,2),
CONSTRAINT ASSIGNPKS PRIMARY KEY (TEST_Date, TestNo , ExamNo),
CONSTRAINT ASSIGNTESTDATE_FK FOREIGN KEY (TEST_Date) REFERENCES TEST(TEST_Date) ON
DELETE CASCADE,
CONSTRAINT ASSIGNTESTNO_FK FOREIGN KEY (TESTno) REFERENCES TESTPAPER (Flightno)
CONSTRAINT TEXAMNo_FK FOREIGN KEY (ExamNo) REFERENCES Exam (ExamNo)
);
May i know where's the issue that it keeps giving me no matching unique primary keys? I already tried to recreate and labelled the 'test_Date' as my primary key. But oracle can't seems to find.
Thanks
The PK you refer to is PRIMARY KEY (TEST_Date, TESTno, ExamNo) — hence the foreign key should be FOREIGN KEY (TEST_Date, TESTno, ExamNo) as well. The error you're getting is due to your attempt to refer to a part of TEST's PK.
See also http://download.oracle.com/docs/cd/B10500_01/server.920/a96524/c22integ.htm
Check the tables you are referencing in your foreign keys. Those columns must be the primary key or otherwise unique on the foreign table.