2

我在一个论坛上工作,就像在每个论坛上一样,有话题和回复。这些是我在数据库中用来存储它们的表:

post
------------
id
user_id
time
type
effective_id

thread
------------
id
update_time
text
response_number
deleted

response
------------
id
container_id
text
deleted

Thepost.type是 a enum('thread', 'response'),并且 the必须根据指示的内容post.effective_id匹配 athread.id或 a 。response.idpost.type

如您所见,我正在分解线程和响应的所有共同点。


这是我遇到的问题:我想确定是否在单个查询id中删除了给定的帖子(将其作为信息)并且不将字段移动到帖子表deleted

如果我事先知道给定的 id 是否属于线程或响应,这些将是我将使用的查询。

SELECT thread.deleted
FROM post INNER JOIN thread ON post.effective_id = thread.id

或者

SELECT response.deleted
FROM post INNER JOIN response ON post.effective_id = response.id

但是我如何在 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.”?我需要某种动态的“如果”

这甚至可能与指定的条件有关吗?

谢谢!

4

2 回答 2

2

查看以下查询中的案例:

SELECT CASE 
WHEN post.type = 'thread' THEN thread.deleted
WHEN post.type = 'response' THEN response.deleted
ELSE 'default'
END
FROM post 
LEFT JOIN thread ON post.effective_id = thread.id
LEFT JOIN response ON post.effective_id = response.id
于 2012-08-25T22:21:19.230 回答
1

使用两个左连接:

SELECT IFNULL(thread.deleted, response.deleted) AS deleted
FROM post
LEFT JOIN thread ON post.effective_id = thread.id
AND post.type = 'thread'
LEFT JOIN response ON post.effective_id = response.id
AND post.type = 'response'
于 2012-08-25T22:19:25.080 回答