Ray Wu
Ray Wu

Reputation: 1033

Two requirements in one query

My table schema looks like this:

table posts (id integer (primary key), parentid integer, tags varchar, ...)

For any post which is the first post in a thread, their parentid is NULL and tags equals to a string. Any other post which is not the first post in a thread, their parentid is id of the first post in that thread and tags is NULL.

I could query all "first posts" of a particular topic by

SELECT * FROM posts WHERE tags LIKE '%topic%';

But how do I query all posts including responses of a particular topic?


assume I have records like this

id   parentid   tags
--------------------
123     null   topic
222     123     null
223     123     null
444     null   topic
555     null   hello

how do I get all ids talking about topic, which are 123, 222, 223, 444?

Upvotes: 0

Views: 120

Answers (1)

GolezTrol
GolezTrol

Reputation: 116190

SELECT * FROM posts 
WHERE tags LIKE '%topic%'
UNION ALL
SELECT * FROM posts 
WHERE PARENTID IN 
  (SELECT ID FROM POSTS WHERE tags LIKE '%topic%')

or

SELECT p.*, r.* FROM posts p
LEFT JOIN posts r ON r.ID = p.ID
WHERE p.tags LIKE '%topic%'

I think the first is cleaner, because it returns one row for the post and one row for each response. The second is easier to implement as a query, but its results are harder to process and it results in more traffic between the database and your script, which is a waste, especially if you've got a separate database server.

Upvotes: 3

Related Questions