avatar
practice JOIN clause with multiple tables MySQL

• Be assumption that we have schema structure for three tables: patients, appointments, and doctors.

CREATE TABLE patients (
  id INT PRIMARY KEY,
  firstname VARCHAR(50),
  lastname VARCHAR(50),
  phone VARCHAR(20),
  email VARCHAR(100)
);

CREATE TABLE appointments (
  id INT PRIMARY KEY,
  patient_id INT,
  doctor_id INT,
  appointment_date DATE,
  appointment_time TIME,
  FOREIGN KEY (patient_id) REFERENCES patients(id),
  FOREIGN KEY (doctor_id) REFERENCES doctors(id)
);

CREATE TABLE doctors (
  id INT PRIMARY KEY,
  name VARCHAR(100),
  specialty VARCHAR(100),
  qualification VARCHAR(100),
  hospital VARCHAR(100)
);

• Let use JOIN for multiple tables and concatenating columns in a SQL query.

$query = $wpdb->prepare(
    "SELECT db.*, dp.phone, dp.email, dd.specialty, dd.qualification, dd.hospital,  CONCAT(dd.firstname, ' ', dd.lastname) AS doctor_name
    FROM `appointments` AS db
    JOIN `patients` AS dp ON db.patient_id = dp.id
    JOIN `doctors` AS dd ON db.doctor_id = dd.id
    WHERE db.id = %d",
    $id
);
You need to login to do this manipulation!