0

Let's say I want to join on 2 tables, one is filled like this.

| Category  |
|-----------|
| id | name |
|----|------|
|  1 | Foo  |
|  2 | Bar  |
|  3 | Baz  |

The other like this:

|   Page    |
|-----------|
| id | cat  |
|----|------|
|  1 | 0    |
|  2 | 1    |
|  3 | 3    |

As you can see cat 0 in the Page table is not present in the Category table. Our system is unfortunately like this and I can't add the category with id 0 to the Category table, due to other code.

Now comes the one million dollar question: Is it possible to join category.id on page.cat and set an if statement when page.cat equals 0 to show the category name as Default?

halfpastfour.am
  • 5,764
  • 3
  • 44
  • 61
Frank Groot
  • 560
  • 6
  • 21

2 Answers2

7

If only 0 is the one missing do a left join and use COALESCE to decode the nulls.

SELECT Page.*, COALESCE(name , 'Default')
FROM Page
LEFT JOIN Category
  ON Page.cat = Category.id;

or

SELECT P.*, IFNULL(C.name , 'Default') as Name   
FROM Page P   
LEFT JOIN Category C ON P.cat= C.id  
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
2

Try this out:

SELECT 
    p.id, 
    p.cat,
    case when p.cat = 0 then "DEFAULT" ELSE c.name END AS cat_name
FROM 
    cat c RIGHT JOIN page p
ON c.id = p.cat
ORDER BY p.id
Rahul Jain
  • 1,319
  • 7
  • 16