MySQL if/条件查询?

MySQL if/条件查询?,mysql,select,join,subquery,Mysql,Select,Join,Subquery,假设我有一个包含以下列的成员资格表: id, first, last, email, type, expires, parentid 其中类型可以是“父”或“子” 如果我查询的id是子id,我如何返回子id的名称信息和父id的过期日期/名称 基本上是这样的: select first, last, email, if (type = "child" select expires, first as parent_first,

假设我有一个包含以下列的成员资格表:

id, first, last, email, type, expires, parentid
其中类型可以是“父”或“子”

如果我查询的id是子id,我如何返回子id的名称信息和父id的过期日期/名称

基本上是这样的:

select 
  first, 
  last, 
  email, 
  if (type = "child"
      select 
      expires, 
      first as parent_first, 
      last as parent_last 
    from members 
    where id = parentid) 
  else ( expires ) 
  from members where id = 100

不要从基于
类型='child'
动态构造SQL的角度来处理它。相反,SQL对相关集进行操作,因此解决方案实际上是对表本身进行
左连接
,以便始终返回父级(尽管有时可能为空)

虽然可以使用带有子选择的
大小写
交替返回父级或子级
expires
,但由于您还需要父级的名称列,因此解决方案是始终返回它们,即使它们可能为
NULL

SELECT
  c.first AS first,
  c.last AS last,
  c.email AS email,
  c.expires AS expires,
  /* parent fields will be NULL if child parentid is NULL */
  p.first AS parent_first,
  p.last AS parent_last,
  p.expires AS parent_expires
FROM
  members c
  /* join against the same table matching 
     parentid of the child to id of the parent */
  LEFT JOIN members p ON c.parentid = p.id
WHERE 
  c.id = 100
使用了
左联接
——因此,如果子级没有
父ID的值
,父列将返回NULL。如果您只希望为
expires
返回一个值,则可以使用
COALESCE()
首选父项,如果父项为空,则返回子项:

SELECT
  ...
  COALESCE(p.expires, c.expires) AS expires,
或者使用
CASE
并检查孩子的
类型(尽管
COALESCE()
更好):


有趣。从编码的角度来看,获取一些可能无法设置的值可能会带来麻烦(比如查询一个不存在的列)…这肯定可以解释为什么我从来没有朝这个方向看。但这就要求我在演示端“if!expires然后parent_expires”,我希望通过始终使用“expires”来避免这种情况。感谢您的回复和解释!:)@不,您不需要在演示端执行“如果!过期,则父项过期”。这就是上面的
COALESCE()
为您处理的问题。如果存在,则返回父过期,否则子过期(假定没有父过期)啊!现在一切都开始有意义了:)再次感谢。
SELECT
  ...
  CASE WHEN c.type = 'child' THEN p.expires ELSE c.expires END AS expires