使用if语句从4个不同的表中选择记录

时间:2017-01-02 11:48:56

标签: mysql sql

 SELECT sup.qid,sup.title ,SUBSTRING(sup.userid, 1, 1) as t ,
 CASE WHEN SUBSTRING(sup.userid, 1, 1) = "s" 
 THEN  select name from staff st where st.id= SUBSTRING(sup.userid, 2, 1) 
 ELSE 
     when SUBSTRING(sup.userid, 1, 1) = "p" 
           THEN  select name from users p where p.id= SUBSTRING(sup.userid, 2, 1)  
   END AS user name 
 FROM `support_queries` sup 

此处,userid将包含uid和前缀,对于工作人员,前缀为 s

对于用户而言 p ,我想获取发布查询的用户详细信息。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

class ThrowingErrorCode
{
public:
    ...
// silence the VC exception specification warning
// we need to use exception specification for a throwing destructor, so that it would compile with both c++98 and c++11
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4290 )
#endif

   ~ThrowingErrorCode() throw(ErrorCodeException)
   {
      ...
      throw ErrorCodeException("Must handle error code");
   }

// enable the warning again
#ifdef _MSC_VER
#pragma warning( pop )
#endif   
};

答案 1 :(得分:0)

我喜欢将此逻辑放入on子句:

SELECT sq.qid, sq.title, LEFT(sup.userid, 1) AS t,
       COALESCE(s.name, u.name) as user_name
FROM support_queries sq LEFT JOIN
     users u
     ON SUBSTRING(sq.userid, 2) = u.id AND
        LEFT(sq.userid, 1) = 'p' LEFT JOIN
     staff s
     ON SUBSTRING(sq.userid, 2) = s.id AND
        LEFT(sq.userid, 1) = 's';

或更简单地说:

SELECT sq.qid, sq.title, LEFT(sup.userid, 1) AS t,
       COALESCE(s.name, u.name) as user_name
FROM support_queries sq LEFT JOIN
     users u
     ON sq.userid = CONCAT('p', u.id) LEFT JOIN
     staff s
     ON sq.userid = CONCAT('s', s.id);