Mysql子查询问题

时间:2010-10-03 13:57:41

标签: mysql mysql-error-1054

  • 贷款(列:id,用户)
  • payback(columns:id,installment,scheduleDate)

如果要分12期支付贷款,那么有12笔贷款ID的回报记录。

我想了解一下用户有一个scheduleDate,他们所有回报的总和都大于2000.

SELECT user 
FROM {loans} ka 
WHERE 
(
   SELECT MAX(inst) FROM 
   (
        SELECT SUM(installment) AS inst 
        FROM {payback} 
        WHERE id IN 
        (
            SELECT id 
            FROM {loans} 
            WHERE user = ka.user
        )  
   GROUP BY scheduleDate
   ) as t1 LIMIT 0,1
) > 2000

我收到错误: 'where子句'中的未知列'ka.user'

1 个答案:

答案 0 :(得分:0)

这是否按要求工作?它假设,payback.id是一个引用loads.id的外键。

SELECT
  user, scheduleDate, sumInstallments
FROM
(
    SELECT
      l.user, pb.scheduleDate, SUM(pb.installment) AS sumInstallments
    FROM
      payback AS pb
    JOIN
      loans AS l
    ON
      l.id = pb.id
    GROUP BY
      l.user, pb.scheduleDate
) AS tempId
WHERE
  sumInstallments > 2000