I’m working on a forum and, like in every forum, there are threads and responses. These are the tables I use in the database to store them:
post
------------
id
user_id
time
type
effective_id
thread
------------
id
update_time
text
response_number
deleted
response
------------
id
container_id
text
deleted
The post.type is an enum('thread', 'response'), and the post.effective_id has to match a thread.id or a response.id according to what the post.type indicates.
As you can see, I’m factorizing everything that the threads and responses have in common.
Here’s the problem I’ve encountered: I want to determine if a given post was deleted (having it’s id as information) in a single query and without moving the deleted field to the post table.
These would be the queries I’d use if I knew beforehand if the given id belongs to a thread or a response.
SELECT thread.deleted
FROM post INNER JOIN thread ON post.effective_id = thread.id
or
SELECT response.deleted
FROM post INNER JOIN response ON post.effective_id = response.id
But how can I say in SQL, “if the post.type is thread then INNER JOIN with thread and get the deleted field, if post.type is response then INNER JOIN with response and get the delete field.“? I’d need some kind of dynamic “if”
Is this even possible to do with the specified conditions?
Thanks!
Take a look at the case in the below query :