Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

sql - compare two dates in Postgressql

I have two table

job1

id(c-v) | joiningDate(character-varying)
--+--
1 | 2020-10-05
2 | 2023-10-05
3 | 2021-01-01

job2

id(c-v) | joiningDate(character-varying)
--+--
1 | 2020-10-05
2 | 2023-10-05

Here is sql query

SELECT max(j1."joiningDate")
    FROM public.job1 j1 left join public.job2 j2 ON j1.id=j2.id and 
    j1."joiningDate"  <= TO_CHAR(CURRENT_DATE, 'YYYY-MM-DD')

I'm trying to fetch the maximum date which is less than current date.. for the I'm getting the empty data.. what would be the issue?

question from:https://stackoverflow.com/questions/65868744/compare-two-dates-in-postgressql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I view the purpose of the join as being a filter on only jobs which match in both tables. If so, then what you really want here is an inner join, and the check on the date being the current date or earlier should be moved to the where clause. Putting this together, perhaps this is what you need here:

SELECT MAX(j1.joiningDate)
FROM public.job1 j1
INNER JOIN public.job2 j2
    ON j1.id = j2.id
WHERE
    j1.joiningDate::date <= CURRENT_DATE;

Note: Consider making the joiningDate column an actual date column in both tables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...