“订单子句”中的MySQL未知列

时间:2017-04-13 10:21:09

标签: mysql stored-procedures

我的MySQL数据库中有一个程序。

我的程序运作正常。但是目前我必须在order by tblUserKeyStatus.createdDate条件中设置IF (opt=1),当我按顺序设置时,它会给我以下错误

Error Code: 1054. Unknown column 'tblUserKeyStatus.createdDate' in 'order clause

我的存储过程如下:

CREATE PROCEDURE proc_GetStatus(IN _userId varchar(64) , IN _qtr int, IN opt int)
BEGIN
    IF (opt = 1) then
        SELECT tblKeyStatus.*,'pending' AS `Status`,'' as scheduleDate,
        ' ' as doneDate,' ' as result FROM tblUserKeyStatus,tblKeyStatus WHERE tblKeyStatus.trimId not in
        (SELECT trimId from tblUserKeyStatus WHERE userId=_userId)
        union
        SELECT tblKeyStatus.*,tblUserKeyStatus.`Status` AS `Status`,tblUserKeyStatus.scheduleDate,
        tblUserKeyStatus.doneDate,tblUserKeyStatus.result FROM tblKeyStatus,tblUserKeyStatus WHERE 
        tblUserKeyStatus.trimId=tblKeyStatus.trimId and tblUserKeyStatus.userId=_userId
        order by tblUserKeyStatus.createdDate;
    Else
        SELECT * from tblKeyStatus WHERE qtr=_qtr;
    End if;
END

2 个答案:

答案 0 :(得分:1)

ORDER BY应用于UNION操作中指定的整个查询,以便UNION返回的整个结果集被排序。

尝试在两个子查询中选择createdDate字段,以便ORDER BY可以访问该字段:

SELECT tblUserKeyStatus.createdDate,
       tblKeyStatus.*,'pending' AS `Status`,
       '' as scheduleDate,
       ' ' as doneDate,
       ' ' as result 
FROM tblUserKeyStatus, tblKeyStatus 
WHERE tblKeyStatus.trimId not in (SELECT trimId 
                                  from tblUserKeyStatus 
                                  WHERE userId=_userId)
UNION

SELECT tblUserKeyStatus.createdDate,
       tblKeyStatus.*,
       tblUserKeyStatus.`Status` AS `Status`,
       tblUserKeyStatus.scheduleDate,
       tblUserKeyStatus.doneDate,tblUserKeyStatus.result 
FROM tblKeyStatus,tblUserKeyStatus 
WHERE tblUserKeyStatus.trimId=tblKeyStatus.trimId and 
      tblUserKeyStatus.userId=_userId
ORDER BY createdDate;

您还必须删除tblUserKeyStatus名称前缀。

答案 1 :(得分:0)

尝试使用大括号进行选择

    CREATE PROCEDURE proc_GetStatus(IN _userId varchar(64) , IN _qtr int, IN opt int)
    BEGIN
        IF (opt = 1) then
            SELECT tblKeyStatus.*,'pending' AS `Status`,'' as scheduleDate,
            ' ' as doneDate,' ' as result FROM tblUserKeyStatus,tblKeyStatus WHERE tblKeyStatus.trimId not in
            ((SELECT trimId from tblUserKeyStatus WHERE userId=_userId)
            union
            (SELECT tblKeyStatus.*,tblUserKeyStatus.`Status` AS `Status`,tblUserKeyStatus.scheduleDate,
            tblUserKeyStatus.doneDate,tblUserKeyStatus.result FROM tblKeyStatus,tblUserKeyStatus WHERE 
            tblUserKeyStatus.trimId=tblKeyStatus.trimId and tblUserKeyStatus.userId=_userId
            order by createdDate));
        Else
            SELECT * from tblKeyStatus WHERE qtr=_qtr;
        End if;
    END