PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 2, 2022

[FIXED] Difference between two columns in mysql

 February 02, 2022     mysql, phpmyadmin, sql     No comments   

Issue

I have two columns (credit and debited_amount) and I want to calculate the difference between them.

Only need to retrieve records greater than zero or if the debited_amount field is Null.

Never mind if the value is zero.

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

Solution

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

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


Answered By - Gordon Linoff
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing