1

我有两个看起来像这样的表:

CREATE TABLE table1 (user_id int, the_date date);
CREATE TABLE table2 (user_id int, the_date date, something_else real);

我正在编写一个看起来像这样的查询

CREATE TABLE foo AS 
 SELECT t1.user_id
 , (t1.the_date - (t2.the_date - t1.the_date)::int) start_date
 FROM table1 t1, table2 t2 
 where t1.user_id=t2.user_id
 ;

当我运行上述查询时,我在 psql 控制台上显示以下错误:

ERROR:  syntax error at or near "$1"
LINE 1: ...the_date - (t2.the_date - t1.the_date)::int)  $1 ...

                                                             ^

查询结果中的第二列是显示一个日期,即N days BEFOREtable1 中的日期,其中 N 是 table2 中的日期与 table1 中的日期之间的差异(以天为单位)。

注意:table2总是有比table1.

如何执行此日期计算并将结果存储为查询中的新列别名?

我正在使用 PG 8.4。

4

1 回答 1

2

您需要表格限定t1.user_id来消除歧义。加上其他调整:

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);
  • 减去两个日期产生整数。演员阵容是多余的。

  • 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 write AS 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.

于 2012-07-18T14:25:29.690 回答