Filter by date using SQL

血红的双手。 提交于 2021-02-17 06:22:26

问题


I would like to know what do you think:

I have to get all the connections I had to the system during a session. To automatize this process, I decided to use current_date%, which won't work because current_date is not a string, it's a function.

So my question is if anyone can help me with the query to get the number of all the connections of the current day.

Thanks in advance!

My shitty code:

SELECT COUNT(id) FROM user_connections
WHERE connectiondate LIKE 'CURRENT_DATE%'

回答1:


The best way (from a performance perspective) is to use logic like this:

WHERE connectiondate >= CURRENT_DATE AND
      connectiondate < CURRENT_DATE + INTERVAL '1 DAY'

Not all databases support ISO/ANSI standard syntax for dates, so the exact expression in your database may differ.




回答2:


You only need connectiondate >= CURRENT_DATE:

SELECT COUNT(id) FROM user_connections
WHERE connectiondate >= CURRENT_DATE

if the data type of connectiondate is datetime.
If it is date then a simple connectiondate = CURRENT_DATE will do.



来源:https://stackoverflow.com/questions/55026314/filter-by-date-using-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!