0

我想从 MySQL 的数据库中选择有关客户余额的最新信息。我写了下一个脚本:

    SELECT *
FROM
    (SELECT        
                    contract_balance.cid,
                    /*contract_balance.yy,
                    contract_balance.mm,*/
                    contract_balance.expenses, 
                    contract_balance.revenues, 
                    contract_balance.expenses + contract_balance.revenues AS total,
                    (CAST(CAST(CONCAT(contract_balance.yy,'-',contract_balance.mm,'-01')AS CHAR) AS DATE)) AS dt
            FROM contract_balance

            /*WHERE                 
                CAST(CAST(CONCAT(contract_balance.yy,'-',contract_balance.mm,'-01')AS CHAR) AS DATE) < '2013-11-01'
            LIMIT 100*/

    ) AS tmp
    WHERE tmp.dt = (
                        SELECT MAX(b.dt)
                        FROM tmp AS b
                        WHERE tmp.cid = b.cid      
                    )

但服务器返回:

表“clientsdatabase.tmp”不存在

如何更改此代码以获取所需数据?

4

2 回答 2

0

在您试图获取的子查询中尝试这个MAX(CAST(CAST(CONCAT(contract_balance.yy,'-',contract_balance.mm,'-01')AS CHAR) AS DATE)) AS dt但在子查询中您的别名表tmp不存在,所以您可以做的最简单的方法是计算MAXdt使用GROUP BY contract_balance.cid承包商 ID,我想它会满足您的需求

SELECT        
contract_balance.cid,
contract_balance.expenses, 
contract_balance.revenues, 
contract_balance.expenses + contract_balance.revenues AS total,
MAX((CAST(CAST(CONCAT(contract_balance.yy,'-',contract_balance.mm,'-01')AS CHAR) AS DATE))) AS dt
FROM contract_balance
GROUP BY  contract_balance.cid
于 2013-12-14T08:48:18.980 回答
0

尝试这个:

SELECT * 
FROM (SELECT cb.cid, cb.expenses, cb.revenues, cb.expenses + cb.revenues AS total, 
            (CAST(CAST(CONCAT(cb.yy,'-',cb.mm,'-01')AS CHAR) AS DATE)) AS dt
      FROM contract_balance cb ORDER BY dt DESC
     ) AS A 
GROUP BY A.cid
于 2013-12-14T08:51:18.380 回答