mysql条件查询

时间:2011-09-13 10:37:46

标签: mysql case conditional-statements

我在mysql数据库中有3个表名为Visits,Groups,Carers。 访问可以由小组或护理人员执行,因此在访问表中我有一个字段护理者模式,如果访问由访问者执行则设置为1,如果由组执行则设置为0。

我需要构建一个语句来检索组名或者看护者名称(取决于carer_mode的值)

我意识到下面的代码不正确,但它可能有助于解释我想要实现的逻辑:

SELECT CASE carer_mode
WHEN  '1' THEN (SELECT name FROM carers WHERE Carers.id = Visits.carer_id )
WHEN '0' THEN (SELECT name FROM groups WHERE Groups.id = Visits.carer_id )
END as carer_name
FROM `Visits`

我很感激任何帮助我实现目标的有效代码的帮助

感谢

凯文

2 个答案:

答案 0 :(得分:2)

您的代码似乎很好。这是获得相同结果的另一种方法:

    SELECT g.name
    FROM 
        Visits AS v
      JOIN
        Groups AS g
          ON g.id = v.carer_id
    WHERE v.carer_mode = 0
UNION ALL
    SELECT c.name
    FROM 
        Visits AS v
      JOIN
        Carers AS c
          ON c.id = v.carer_id
    WHERE v.carer_mode = 1

答案 1 :(得分:0)

我认为这会奏效:

  select 
  case carer_mode when '1' then c.name 
  else g.name end as carer_name 
  from Carer c 
  left join Visits v on v.carer_id=c.carer_id 
  left join Groups g on g.carer_id=c.carer_id