1

I have a table called Post:

title (NULL), content, parent_id (NULL)

The title is null because I use this for threads and replies (replies do not have a title and threads do not have a parent).

Say I want to select all the replies to post x, or an n number of replies:

SELECT * FROM post
WHERE title IS NULL
AND parent_id = x

or,

SELECT * FROM post
WHERE title IS NULL
AND parent_id IS NOT NULL
LIMIT 0, 30

How can I also select the title of a reply? Say for example if I select reply number 5 and it's a reply to post id# 2 (i.e has parent_id of 2), how can I select the title of number 2?

I don't want to use a foreach loop in mysql.

Hope this makes sense.

Thank you.

1
  • Do you know if this would be more than one level deep? As is already discussed, a single join would solve your problem if replies can only be added to a Post with a title (i.e. not another reply). Commented May 4, 2011 at 2:34

3 Answers 3

1

COALESCE returns first value of an argument list that is not null.

   SELECT post.content, COALESCE(post.title, parent.title) AS title
     FROM post
LEFT JOIN post AS parent
       ON post.parent_id = parent.id
    WHERE post.parent_id = 123
Sign up to request clarification or add additional context in comments.

Comments

1

I'd join from your post table into your post table. It's fun. (This assumes that your post table has an id column, which corresponds to parent_id)

SELECT child.*, parent.title FROM post child JOIN post parent ON (child.parent_id=parent.id)

Comments

1

Assuming your Post table structure looks like:

+-----+------------+-----------------+----------+
| id  | parent_id  | title           | content  |
+-----+------------+-----------------+----------+
| 1   |  NULL      | Post #1 Title   | ...      |
+-----+------------+-----------------+----------+
| 2   |  NULL      | Post #2 Title   | ...      |
+-----+------------+-----------------+----------+
| 3   |   1        |                 | ...      |
+-----+------------+-----------------+----------+
| 4   |   2        |                 | ...      |
+-----+------------+-----------------+----------+

You need to use a join:

SELECT
   *, parent.title AS parent_title
FROM
   post
LEFT JOIN
   post as parent ON parent.id = post.parent_id
WHERE
   post.id = 4

That would select post id=4 and also get you the title of post id=2 stored in the field parent_title

1 Comment

#1052 - Column 'id' in where clause is ambiguous

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.