\! clear;

DROP TABLE IF EXISTS Medecin, Patient, Consultation, Medicament, Laboratoire ,Posologie ,Fournir;

CREATE TABLE Medecin (
	id_medecin numeric PRIMARY KEY,
	nom varchar NOT NULL,
	prenom varchar NOT NULL
);

CREATE TABLE Patient (
	num_pat numeric PRIMARY KEY,
	nom varchar NOT NULL,
	prenom varchar NOT NULL,
	age numeric CHECK (age is NULL OR age > 0)
);

CREATE TABLE Consultation (
	num_cons varchar PRIMARY KEY CHECK (num_cons LIKE 'C%'),
	date date,
	heure time,
	id_medecin numeric, 
	num_pat numeric,
	FOREIGN KEY (id_medecin) REFERENCES Medecin,
	FOREIGN KEY (num_pat) REFERENCES Patient
);


CREATE TABLE Medicament (
	num_med numeric PRIMARY KEY,
	nom varchar NOT NULL UNIQUE,
	prix numeric CHECK (prix > 0) 
);

CREATE TABLE Posologie (
	matin numeric CHECK (matin is NULL or matin > 0),
	midi numeric CHECK (midi is NULL or midi > 0),
	soir numeric CHECK (soir is NULL or soir > 0),
	num_cons varchar,
	num_med numeric,
	PRIMARY KEY(num_cons, num_med),
	FOREIGN KEY (num_med) REFERENCES Medicament,
	FOREIGN KEY (num_cons) REFERENCES Consultation
);

CREATE TABLE Laboratoire (
	num_lab numeric PRIMARY KEY,
	nom varchar NOT NULL UNIQUE,
	rue numeric,
	code_postal numeric(5) CHECK ((code_postal IS NOT NULL) = (pays = 'France')), /*<=> (code_post IS NOT NULL AND pays IS 'France') OR (code_postal IS NULL AND Pays IS NOT 'France')*/
	ville varchar,
	pays varchar DEFAULT ('France')
);

CREATE TABLE Fournir (
	num_lab numeric,
	num_med numeric,
	PRIMARY KEY (num_lab, num_med),
	FOREIGN KEY (num_lab) REFERENCES Laboratoire,
	FOREIGN KEY (num_med) REFERENCES Medicament
);

SELECT * FROM Medecin ORDER BY nom, prenom ASC;

SELECT * FROM Patient WHERE age < 18 ORDER BY nom, prenom DESC;

SELECT Consultation.* FROM Consultation JOIN Posologie ON Consultation.num_cons = Posologie.num_cons WHERE soir IS NOT NULL;

SELECT Consultation.* FROM Consultation JOIN Posologie ON Consultation.num_cons = Posologie.num_cons WHERE matin > (midi + soir);

SELECT Laboratoire FROM 

