Relate fields in SQL

2

I am creating a Database in MYSQL to use it in a Java program, I put you as I have created the first two tables for the moment:

create table cliente(
id_cliente int,
Nombre varchar(255),
Apellido varchar(255),
DNI varchar(20),
Calle varchar(255),
Num_calle int,
Piso varchar(10),
Localidad varchar(255),
Provincia varchar(255),
Telefono int,
id_vehiculo int,
constraint pk_id_cliente primary key (id_cliente)
);

create table vehiculos(
id_vehiculo int,
Marca varchar(30),
Modelo varchar(30),
Cilindrada int,
KW int,
num_chasis int,
anyo int,
kilometros int,
constraint pk_id_vehiculo primary key (id_vehiculo)
);

In my program, when adding a customer to the BD, you can create it with or without a vehicle associated with it, and if you want later, add the vehicle if you have not done it or add another one, that is, I can have two, here comes my dilemma; in the BD I want the field'id_vehicle 'of the client to be filled in with the field'id_vehicle' when adding the vehicle to the client, but of course, I also want that when creating the client, if I do it without a vehicle , that field is empty until I decide to add a vehicle; and I do not know how to make those relationships.

    
asked by NeoChiri 07.09.2016 в 19:24
source

2 answers

2

One option that you have, is to create a third table for example Clients-vehicles, in which you create that relationship. In principle with the fields id_cliente e id_vehiculo , they would be enough.

create table clientes-vehiculos(
id int,
id_vehiculo int,
id_cliente int,
constraint pk_id primary key (id)
);

The id field is for my pleasure that I prefer to have a key field, instead of having to be mixing data for a primary key

    
answered by 07.09.2016 / 19:39
source
0

I would only make these changes in the Query and that's it. Also, the field id_vehicle in client would accept the value null so you could leave it empty until you decide to use it.

create table vehiculos(
id_vehiculo int not null auto_increment,
Marca varchar(30),
Modelo varchar(30),
Cilindrada int,
KW int,
num_chasis int,
anyo int,
kilometros int,
PRIMARY KEY(id_vehiculo)
);

create table cliente(
id_cliente int not null auto_increment,
Nombre varchar(255),
Apellido varchar(255),
DNI varchar(20),
Calle varchar(255),
Num_calle int,
Piso varchar(10),
Localidad varchar(255),
Provincia varchar(255),
Telefono int,
id_vehiculo int,
PRIMARY KEY(id_cliente),
FOREIGN KEY (id_vehiculo) REFERENCES vehiculos(id_vehiculo)
);
    
answered by 08.09.2016 в 01:48