Where The Streets Have No Name

선택적 조인 mysql 버전 본문

Developement/DataBase

선택적 조인 mysql 버전

highheat 2012. 9. 25. 17:33
CREATE TABLE `t_contact` (
  `customer_id` varchar(100) NOT NULL DEFAULT '',
  `telno` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`customer_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;​
CREATE TABLE `t_customer` (
  `customer_id` varchar(100) NOT NULL DEFAULT '',
  `name` varchar(100) DEFAULT NULL,
  `customer_type` varchar(100) DEFAULT NULL,
  `sno` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`customer_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `t_company` (
  `customer_id` varchar(100) NOT NULL DEFAULT '',
  `size_cd` varchar(100) DEFAULT NULL,
  `employee_cnt` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`customer_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `t_person` (
  `customer_id` varchar(100) NOT NULL DEFAULT '',
  `hobby_cd` varchar(100) DEFAULT NULL,
  `religion_cd` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`customer_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
select a.customer_id,
       a.customer_type,
       b.hobby_cd,
       b.religion_cd,
       c.size_cd,
       c.employee_cnt, 
       d.telno 
  from t_customer a 
     left outer join t_person b 
         on if(a.customer_type='1',a.customer_id,null) = b.customer_id 
     left outer join t_company c 
         on if(a.customer_type='2',a.customer_id,null) = c.customer_id 
     left outer join t_contact d 
         on a.customer_id = d.customer_id ;