I have two tables that look like this:
CREATE TABLE table1 (user_id int, the_date date);
CREATE TABLE table2 (user_id int, the_date date, something_else real
You would need to table-qualify t1.user_id
to disambiguate. Plus 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.
Don't omit the AS
keyword for column aliases - while it's generally OK to omit AS
for table aliases. The manual:
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 writeAS
or double-quote the output name.)
Joining tables with a USING
clause only keeps one instance of the joining columns(s) (user_id
in this case) in the result set and you don't have to table-qualify it any more.