Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在SQL中执行动态if语句?_Mysql_Sql_Select_Inner Join - Fatal编程技术网

Mysql 如何在SQL中执行动态if语句?

Mysql 如何在SQL中执行动态if语句?,mysql,sql,select,inner-join,Mysql,Sql,Select,Inner Join,我在一个论坛上工作,就像在每个论坛上一样,都有帖子和回复。以下是我在数据库中用于存储它们的表: post ------------ id user_id time type effective_id thread ------------ id update_time text response_number deleted response ------------ id container_id text deleted post.type是一个enum('thread','respo

我在一个论坛上工作,就像在每个论坛上一样,都有帖子和回复。以下是我在数据库中用于存储它们的表:

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

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

response
------------
id
container_id
text
deleted
post.type
是一个
enum('thread','response')
post.id
必须根据
post.type
的指示匹配
thread.id
response.id

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


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

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

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

但是在SQL中,我怎么能说,“
如果post.type是thread,那么内部连接thread并获取已删除字段;如果post.type是response,那么内部连接response并获取删除字段。
”?我需要一些动态的“如果”

在特定的条件下,这可能吗

谢谢

使用两个左连接:

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'

请查看以下查询中的案例:

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