2

I'm sorry if I don't know the correct terminology but here we go:

I have a table with the following columns and rows:

------------------------------
| id    | parent_id  | type  |
------------------------------
| 1     | 0          | text1 |
| 2     | 1          | text2 |
------------------------------

Now what I want is to select the type, but if the parent_id is not 0 I want the type to be the content of the type from it's parent +[ the type of itself ].

So the output for a select would in this case be:

----------------
| type         |
----------------
| text1        |
| text1[text2] |
----------------

I was trying this with a concat and an if statement, but couldn't figure this out.

Can you help me out?

1
  • Will this only be for the immediate parent, or do you want to include the ultimate ancestor? (The latter is problematic in MySQL.) Commented Apr 11, 2013 at 9:42

1 Answer 1

4

Try:

select c.id,
       case c.parent_id 
            when 0 then c.type
            else concat(p.type,'[',c.type,']')
       end as type
from mytable c
left join mytable p on c.parent_id = p.id

SQLFiddle here.

Sign up to request clarification or add additional context in comments.

3 Comments

shouldn't be case parent_id there?
Super thanks! Now can you also do a where here? or is this not possible because of the if statement in there?
@BonifatiusK: You should be able to do a where here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.