Saturday, April 4, 2009

SQL Left Join Twice

Say if you have two category id for a logo {logoId, logoCode }, and the category {catId,catDescription} belongs to another table with a link on table {catId, logoId} we need to left join on each logo twice, so that we can get the logo category as a single row. The SQL is as follows:

SELECT `categoryLinksId`, `_category`.`catId` as `pcatId`, `_category`.`catName` as `pcatName`, `category1`.`catId` as `ccatId`, `category1`.`catName` as `ccatName` FROM (`_categorylinks` LEFT JOIN `_category` ON `_categorylinks`.`parent_categoryId` = `_category`.`catId`) LEFT JOIN `_category` as `category1` ON `_categorylinks`.`child_categoryId` = `category1`.`catId`

No comments: