从CASE MySQL中嵌套的SELECT中返回多个列

时间:2010-08-29 22:58:39

标签: sql mysql case

有更好的方法吗?

SELECT subs. * ,
       CASE subs.member_type
         WHEN 'member' THEN 
         ( SELECT CONCAT_WS( ' ', members.first_name, members.last_name )
             FROM members
            WHERE members.id = subs.member_id)
         ELSE 
         ( SELECT members_anon.username
             FROM members_anon
            WHERE members_anon.id = subs.member_id)
       END AS fullname,
       CASE subs.member_type
         WHEN 'member' THEN 
         ( SELECT members.email
             FROM members
            WHERE members.id = subs.member_id)
         ELSE 
         ( SELECT members_anon.email
             FROM members_anon
            WHERE members_anon.id = subs.member_id)
       END AS email
  FROM subs
 WHERE subs.item_id =19
   AND subs.item_type = 'blog'
 LIMIT 0 , 30

理想情况下,我希望只有一个CASE部分从相关表中返回姓名和电子邮件。

2 个答案:

答案 0 :(得分:4)

我会在两个表上使用左外连接:

SELECT subs. * ,
       CASE subs.member_type
         WHEN 'member' THEN CONCAT_WS( ' ', m.first_name, m.last_name )
         ELSE ma.username
       END AS fullname,
       CASE subs.member_type
         WHEN 'member' THEN m.email
         ELSE ma.email
       END AS email
  FROM subs
  LEFT OUTER JOIN members m on (m.id = subs.member_id)
  LEFT OUTER JOIN members_anon ma on (ma.id = subs.member_id)
 WHERE subs.item_id =19
   AND subs.item_type = 'blog'
 LIMIT 0 , 30

关于只有一个案例的愿望,如果您的结果集需要两个不同的列,则需要两个case个句子。

答案 1 :(得分:2)

您不能使用单个案例表达式来处理两个单独的列...

使用:

   SELECT s. *,
          CASE s.member_type
            WHEN 'member' THEN x.fullname
            ELSE y.fullname
          END AS fullname,
          CASE subs.member_type
            WHEN 'member' THEN x.email
            ELSE y.email
          END AS email
     FROM SUBS s
LEFT JOIN (SELECT m.id,
                  CONCAT_WS( ' ', members.first_name, members.last_name ) AS fullname,
                  m.email
             FROM MEMBERS m) x ON x.id = s.member_id
LEFT JOIN (SELECT ma.id,
                  ma.username,
                  ma.email
             FROM MEMBERS_ANON ma) y ON y.id = s.member_id                         
    WHERE s.item_id = 19
      AND s.item_type = 'blog'
    LIMIT 0 , 30