phpmyadmin mysql中两列的区别

jv4diomz  于 2022-11-09  发布在  PHP
关注(0)|答案(1)|浏览(146)

我有两列(creditdebited_amount),我想计算它们之间的差值。
仅当debited_amount字段为Null时,才需要检索大于零的记录。
如果值为零,则不必在意。
下面是我尝试过的SQL查询。请帮助

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();
dwthyt8l

dwthyt8l1#

您只需要将逻辑添加到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);

您的查询在select中重新定义了credit。但是,这是不相关的,因为您不能在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);

相关问题