我有两张桌子,分别是tb1个号和tb2个号.tb2个通过名为tk_id的外键连接到tb1个.下面是我的两张桌子的外观
tb1个
Column | Type | Collation | Nullable | Default
-----------------+-----------------------------+-----------+----------+--------------------------------------------------
id | integer | | not null | nextval('tb2_id_seq'::regclass)
created_at | timestamp without time zone | | not null |
modified_at | timestamp without time zone | | not null |
status | double precision | | not null |
tk_id | uuid | | not null |
tb2个
Column | Type | Collation | Nullable | Default
----------------+-----------------------------+-----------+----------+---------
id | uuid | | not null |
created_at | timestamp without time zone | | not null |
modified_at | timestamp without time zone | | not null |
destination_id | uuid | | not null |
source_id | uuid | | not null |
tk_id | uuid | | not null |
Now I need to get all rows from tb1个 which has columns from both tb1个 and tb2个 when the tk_id value matches for both the rows.
这就是我try 过的:
select tb1.created_at, tb1.status, tb2.source_id, tb2.destination_id from tb1
inner join tb2 on tb1.tk_id = tb2.tk_id where
tb1.created_at > timezone('utc', now()) - interval '40 minutes';
但我排得太多了.通常在40min个间隔中,大约有800条记录,但在联接之后,我得到了大约100,000+条记录.
在一些阅读和几次try 之后,我对查询进行了一些更改,并设法将行减少到预期的行数.这是我现在的疑问
SELECT count(*) FROM tb1 LEFT OUTER JOIN (SELECT DISTINCT tk_id FROM tb2) t2
ON tb1.tk_id = t2.tk_id where tb1.created_at > timezone('utc', now()) -
interval '40 minutes';
But now I can't get the columns of tb2个 in my select query.
我做错了什么?
EDIT2: Sorry if I couldn't make this clearer earlier. The join condition should be based on the latest occurrence of tk_id of the right table. So for every row of left table (tb1个), it should match against the latest occurrence of tk_id of right table (tb2个) and fetch the right table's columns.