Difference between two columns in mysql(mysql中两列的区别)
问题描述
我有两列(credit
和 debited_amount
),我想计算它们之间的差异.
I have two columns (credit
and debited_amount
) and I want to calculate the difference between them.
只需要检索大于零或 debited_amount
字段为 Null 的记录.
Only need to retrieve records greater than zero or if the debited_amount
field is Null.
不要介意值是否为零.
这是我尝试过的 SQL 查询.请帮忙
Here is the SQL query which I have tried. Please help
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();
推荐答案
你只需要在where
子句中添加逻辑即可:
You just need to add the logic into the where
clause:
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
就是它使用的.如果添加表别名就更清楚了:
Your query redefines credit
in the select
. However, that is irrelevant, because you can't refer to a column alias in the where
clause. So, the column credit
is what it used. It is clearer if you add table aliases:
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);
这篇关于mysql中两列的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:mysql中两列的区别


基础教程推荐
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01