mysql中两列之间的区别

时间:2014-08-01 10:13:33

标签: mysql sql phpmyadmin

我有两列(credit和debited_amount),我想计算它们之间的差异。只需要检索大于零的记录或者debited_amount字段为Null。没关系,如果值为零。这是我试过的sqlquery。请帮助

SELECT `p_Id`,`user_id`,`doc_id`,`credit` ,`app_date`,`expires_on`,(credit -debited_amount) AS credit
FROM `wp_loyalty_credits` WHERE `expires_on`>now();

1 个答案:

答案 0 :(得分:1)

您只需将逻辑添加到where子句中:

SELECT `p_Id`,`user_id`,`doc_id`,`credit` ,`app_date`,`expires_on`,
       (credit -debited_amount) AS credit
FROM `wp_loyalty_credits`
WHERE `expires_on`>now() and (credit > debited_amount or debited_amount is null);

您的查询会在credit中重新定义select。但是,这是无关紧要的,因为您无法在where子句中引用列别名。因此,列credit就是它所使用的。如果添加表别名则更清楚:

SELECT lc.p_Id, lc.user_id, lc.doc_id, lc.credit, lc.app_date, lc.expires_on,
       (lc.credit - lc.debited_amount) AS credit
FROM `wp_loyalty_credits` lc
WHERE lc.expires_on > now() and
      (lc.credit > lc.debited_amount or lc.debited_amount is null);