I want to retrieve all ids within a certain timespan. The timestamps however, are stored in a different table:

Table A has column  my_id
Table B has columns my_id, timestamp

I would want something like

SELECT
  id,
  time
FROM
  (SELECT my_id AS id FROM A) q1,
  (SELECT timestamp AS time FROM B WHERE my_id = id) q2
;

But how can I get the value of id within a different subquery? Is there an elegant solution for this problem?

有帮助吗?

解决方案

I see that in the second subquery you try to link the two tables:

(SELECT my_id AS id FROM A) q1,
(SELECT timestamp AS time FROM B WHERE my_id = id) q2

If both ids must be equals:

SELECT a.my_id as id, b.timestamp as time
FROM A a
JOIN B b ON (a.my_id = b.my_id);

I hope this helps.

其他提示

Simpler:

SELECT my_id AS id, b.my_ts
FROM   a
JOIN   b USING (my_id);
  • FROM A a (like has been advised) is nonsense because, I quote the manual:

Quoting an identifier also makes it case-sensitive, whereas unquoted names are always folded to lower case.

  • While being allowed in PostgreSQL, the type names time and timestamp are reserved words in every SQL standard and should not be used as identifiers.

  • USING is a syntactical shorthand, mostly.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top