2012-08-25 31 views
2

我正在論壇上工作,就像在每個論壇上一樣,有線程和響應。這些都是我在數據庫中使用存儲它們的表:如何在SQL中執行動態if語句?

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

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

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

post.typeenum('thread', 'response'),並且post.effective_id有根據什麼post.type指示匹配thread.idresponse.id。正如你所看到的,我將線程和響應的共同點分解了一切。


下面是我碰到的問題:我想確定給定的帖子被刪除(有它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.」 說什麼?我需要一些動態的「如果」

這甚至可以用指定的條件嗎?

謝謝!

回答

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 
+0

這正是我一直在尋找,謝謝! – federicot

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'