Date column arithmetic in PostgreSQL query

允我心安 提交于 2019-12-02 08:23:37
Erwin Brandstetter

As @LisMorski commented, you would need to table-qualify t1.user_id to disambiguate the way you have it.

I would also suggest a couple of other adjustments:

CREATE TABLE foo AS 
 SELECT user_id
       ,(t1.the_date - (t2.the_date - t1.the_date)) AS start_date
 FROM table1 t1
 JOIN table2 t2 USING (user_id);
  • Subtracting two dates yields integer. Cast was redundant.

  • For column aliases it's best to use the AS keyword (while it's generally OK to omit it for table aliases). I quote the manual here:

You can omit AS, but only if the desired output name does not match any PostgreSQL keyword (see Appendix C). For protection against possible future keyword additions, it is recommended that you always either write AS or double-quote the output name.)

  • If you join your tables with an explicit JOIN clause us9ing the USING keyword, then there is only one column user_id in the result set and you don't have to table-qualify it any more.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!