How to directly compare two generated columns in the SELECT clause from mySQL [duplicate]

oo7oh9g9  于 2022-12-22  发布在  Mysql
关注(0)|答案(1)|浏览(111)

This question already has answers here:

Unable to ALIAS a simple CASE statement (2 answers)
Closed 1 hour ago.
I'm wondering if there is a concise way to compare the equality of two generated columns in mySQL.
Say I have the following query:

SELECT id,
       date, date_a, date_b,
       DATE_DIFF(date, date_a, DAY) AS datediff_a,
       DATE_DIFF(date, date_b, DAY) AS datediff_b
FROM data

Here, I want to generate another column that shows the equality of datediff_a and datediff_b . Hence, I add the following line in the same SELECT clause:

CASE WHEN datediff_a = datediff_b THEN 0 ELSE 1 END AS diff

This, however, returns an invalidQuery error, as it does not recognize the name datediff_a (and probably datediff_b ).
Is there a way to directly insert the comparison column in my SELECT clause?

nxowjjhe

nxowjjhe1#

Because your query syntax is wrong, you're selecting data on the table and returning those then you write your cases, it's wrong, you should write your cases after you selected your columns like the following syntax:

SELECT
  `date_a`, `date_b`,
  CASE
    WHEN `date_a` = `date_b` THEN 
      "Your dates are equal"
    ELSE "Your dates are different"
  END as date_comparison
FROM `data`;

相关问题