在CASE上选择语句

时间:2014-07-09 07:40:05

标签: mysql sql select case

您好我试图从一个表返回一个结果集。但是,我想在结果集上添加另一个列,它来自另一个表。

SELECT ID, NAME,
       CASE (SELECT STATUS FROM OTHERTABLE O WHERE O.ID = M.ID)
          WHEN '1' THEN 'In progress'
          WHEN '2' THEN 'Complete'
       END as STATUS
FROM MAINTABLE M

我收到错误: 子查询返回的值超过1。这是不允许的......等等。

5 个答案:

答案 0 :(得分:2)

使用加入并整理案例

SELECT 
  M.ID,
  M.NAME,
  CASE
    WHEN O.STATUS = '1' 
    THEN 'In progress' 
    WHEN O.STATUS = '2' 
    THEN 'Complete' 
  END AS STATUS 
FROM
  MAINTABLE M 
  JOIN OTHERTABLE O 
    ON (O.ID = M.ID)

答案 1 :(得分:1)

这是因为您的MainTable Id在OtherTable中有多条记录

试试吧

SELECT ID, NAME,
   CASE 
      WHEN O.STATUS = '1'  THEN 'In progress'
      WHEN O.STATUS = '2' THEN 'Complete'
   END as STATUS
FROM MAINTABLE M JOIN OTHERTABLE O ON O.Id = M.ID

答案 2 :(得分:1)

你可能想要这个

SELECT ID, NAME,
       CASE WHEN O.STATUS = '1' THEN 'In progress'
            WHEN O.STATUS = '2' THEN 'Complete'
       END AS STATUS
FROM MAINTABLE M
INNER JOIN OTHERTABLE O ON O.ID = M.ID

答案 3 :(得分:1)

在这种情况下,您需要一个连接,而不是一个子查询:

SELECT ID, NAME,
CASE O.STATUS 
  WHEN '1' THEN 'In progress'
  WHEN '2' THEN 'Complete'
END as STATUS
FROM MAINTABLE M
INNER JOIN OTHERTABLE O ON O.ID = M.ID;

答案 4 :(得分:0)

您应该根据错误消息使用限制1。

SELECT M.ID, M.NAME,
    CASE WHEN O.STATUS = '1' THEN 'In progress'
         WHEN O.STATUS = '2' THEN 'Complete' 
    END as STATUS
FROM MAINTABLE M INNER JOIN OTHERTABLE O ON O.ID = M.ID LIMIT 1