Determine if "item" in parent table or child table

just to follow up on this idea, of using 0 as the FK to avoid a NULL, try this simple experiment –

CREATE 
  TABLE categories
      ( category_id SMALLINT     NOT NULL PRIMARY KEY
      , name        VARCHAR(255) NOT NULL
      , parent      SMALLINT     NOT NULL
      , CONSTRAINT valid_parent
          FOREIGN KEY ( parent )
            REFERENCES categories ( category_id )
      );      

you will see that the structure is perfectly reasonable, the parent column is declared NOT NULL so that you can use a 0

now go ahead and insert a row, i’ll wait

NULL !!!

I’ll see.

I am trying to change column name, based if parent or child, BUT I keep failing.

CASE WHEN c.parent = NULL THEN 
CASE WHEN c.parent != NULL THEN

use IS or IS NOT – there is no equals

Yes, I did that too.

CASE WHEN c.parent IS NULL THEN c.name END AS Child,
CASE WHEN c.parent IS NOT NULL THEN c.name END AS Parent

The issue is that I am getting both of them.

i think you need to go back to the manual and check the actual syntax for a CASE expression – you’re missing something

1 Like

DO I need IF or something?
E.g. ternary operator ?

let me assure you that the answer is in the manual

i will not look it up for you, you need to learn how to do that yourself

1 Like

Which manual?

Sure. But there’s NOTHING about setting different column alias. Sorry.

https://dev.mysql.com/doc/refman/5.7/en/case.html

That’s what I’ve been doing:

CASE WHEN 
c.parent IS NULL THEN c.name
END AS Child, 
CASE WHEN 
c.parent IS NOT NULL THEN c.name 
END AS Parent

BUT HOW DO I GET ONLY ONE OF THEM IN THE OUTPUT?

SELECT c.name
     , CASE WHEN c.parent IS NULL
            THEN 'parent'
            ELSE 'child' END AS what_it_be
  FROM ...
1 Like

I see your approach. BUT, is it possible to modify column alias and output only one?

nope

1 Like

I see, thx.

Hi, why isn’t this SQL working as expected?

SELECT i.*, 
 parent.name AS 'Parent', 
 child.name AS 'Child'
 FROM items i
 LEFT JOIN categories child ON i.category_id = child.category_id
 LEFT JOIN categories parent ON child.parent = parent.category_id
 WHERE i.name = "Pepsi";

I am getting Parent = NULL, while Child equals the name of the Parent. Is there something wrong in my order of LEFT JOINs ?

So I will assume your table still has Pepsi in the category Pepsi, which has no parent.

LEFT JOIN categories child ON i.category_id = child.category_id
So, “Pepsi”'s category id matches the category ID for “Pepsi”. (Naming your item and your category the same is going to make this confusing.)

LEFT JOIN categories parent ON child.parent = parent.category_id
The Pepsi category’s parent field is NULL. so this doesnt join anything; or rather, it joins no data to the new columns.

parent.name, then, is NULL.
child.name, is Pepsi.

This is expected behavior.

1 Like

Ah. Didn’t know this.

Pepsi = Parent main category.
Pepsi Zero = Child category.

Is there a way to overcome?