Pages

Friday, January 25, 2013

Mysql Insert From Cross Join

Think of a scenario like this, we have a database of Doctors and Patients. All the doctors have access to all the patients information and all the patients can visit any doctor.
-- ----------------------------------------
-- Table `Doctors`
-- ----------------------------------------
CREATE TABLE IF NOT EXISTS `Doctors` (
  `doc_id` int(10) unsigned NOT NULL,
  `doc_first_name` VARCHAR(104) NOT NULL,
  `doc_last_name` VARCHAR(104) NOT NULL,
  `doc_discipline` VARCHAR(104) NOT NULL,
  PRIMARY KEY (`doc_id`)
) 
ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Doctors` VALUES(1,'Sintu', 'Kumar', 'otholaringology');
INSERT INTO `Doctors` VALUES(2,'R', 'Chinch', 'dentistry');
-- ----------------------------------------
-- Table `Patients`
-- ----------------------------------------
CREATE TABLE IF NOT EXISTS `Patients` (
  `p_id` int(10) unsigned NOT NULL,
  `p_first_name` VARCHAR(104) NOT NULL,
  `p_last_name` VARCHAR(104) NOT NULL,
  PRIMARY KEY (`p_id`)
) 
ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Patients` VALUES(1,'Jim','Cary');
INSERT INTO `Patients` VALUES(2,'John','Cook');
-- ----------------------------------------
-- Table `Doctors_Patients`
-- ----------------------------------------
CREATE TABLE IF NOT EXISTS `Doctors_Patients` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `doctor_id` int(10) unsigned NOT NULL,
  `patient_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`doctor_id`) REFERENCES `Doctors` (`doc_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  FOREIGN KEY (`patient_id`) REFERENCES `Patients` (`p_id`) ON DELETE NO ACTION ON UPDATE NO ACTION

) 
ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now we want to populate the table `Doctors_Patients` with the Cartesian  product of the other two tables. For this we can simply use cross join as listed below.

INSERT INTO `Doctors_Patients`(doctor_id,patient_id) SELECT `doc_id`, `p_id` FROM `Doctors`  CROSS JOIN `Patients`;

And this is what it did.
select * from Doctors_Patients;

+----+-----------+------------+
| id | doctor_id | patient_id |
+----+-----------+------------+
|  1 |         1 |          1 |
|  2 |         2 |          1 |
|  3 |         1 |          2 |
|  4 |         2 |          2 |
+----+-----------+------------+
4 rows in set (0.08 sec)

No comments:

Post a Comment