MySQL按子查询列排序

时间:2015-03-05 15:32:31

标签: mysql sql subquery where

我的SQL查询有问题。我们的想法是选择支付后的所有贷款(状态1/2/3),在8到21天之间,从pay_day到现在的计算值。

我已经完成了一些查询但不能在WHERE部分使用days_after_payment和days_after_part_payment列。我想根据贷款类型设置一个像days_after_payment这样的列。

SELECT l.*,
(SELECT SUM(`value`) FROM `loan_part` WHERE `loan_id` = l.id AND `paid`=0) AS left_to_pay, 
-(DATEDIFF((SELECT date FROM `loan_part` WHERE `loan_id` = l.id AND `paid`=0 AND `date`<CURDATE() ORDER BY `date` LIMIT 1), NOW())) AS days_after_part_payment,
-(DATEDIFF(l.payment_date, NOW())) AS days_after_payment
FROM loan l
WHERE (l.type=1 or l.type=2) AND (l.status=1 OR l.status=2 OR l.status=3)
GROUP BY l.client_id
ORDER BY 
CASE l.type 
    WHEN 1 THEN days_after_payment
    WHEN 2 THEN days_after_part_payment
    ELSE 1 END 
ASC

CREATE TABLE IF NOT EXISTS `loan` (
  `id` int(11) NOT NULL,
  `value` int(11) NOT NULL,
  `client_id` int(11) NOT NULL,
  `status` int(11) NOT NULL,
  `type` int(11) NOT NULL,
  `payment_date` date DEFAULT NULL  
) ENGINE=MyISAM AUTO_INCREMENT=2068 DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `loan_part` (
`id` int(10) unsigned NOT NULL,
  `loan_id` int(11) NOT NULL,
  `value` float NOT NULL,
  `date` date DEFAULT NULL,
  `paid` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=MyISAM AUTO_INCREMENT=1751 DEFAULT CHARSET=utf8;

Update1:​​我不得不删除不必要的列并用我的母语将其重写为英语。

1 个答案:

答案 0 :(得分:0)

ORDER BY 7

&#34; 7&#34;表示SELECT中的第7个字段。这也适用于GROUP BY。我必须看到表格定义来计算l.*中的数量。

如何id未声明AUTO_INCREMENT