简体   繁体   English

PostgreSQL:外部和自我连接

[英]PostgreSQL: Outer and self join

I want to do an outer join on the same table, but I'm getting unexpected results. 我想在同一张桌子上做一个外部联接,但是得到了意外的结果。

This is what my "stock" table looks like: 这是我的“股票”表的样子:

price_timestamp,            security,   price_type, open,  high, low,  close
"2014-05-01 00:00:00-07";"SPY US EQUITY";"ASK";     188.54;188. 57;188.54;188.57
"2014-05-01 07:59:00-07";"SPY US EQUITY";"ASK";     188.72;188. 72;188.72;188.72
"2014-05-01 08:01:00-07";"SPY US EQUITY";"ASK";     188.71;188. 72;188.71;188.72
"2014-05-01 13:30:00-07";"SPY US EQUITY";"TRADE";   188.22;188. 27;188.21;188.26
"2014-05-01 13:31:00-07";"SPY US EQUITY";"TRADE";   188.27;188. 35;188.26;188.35
...

price_type can be BID, ASK or TRADE. price_type可以是BID,ASK或TRADE。 I want a query that returns price_timestamp, security, bid price (which would be close price where price_type = 'BID'), and trade price (which would be close price where price_type = 'TRADE). 我想要一个查询,该查询返回price_timestamp,安全性,买入价(在price_type ='BID'时为收盘价)和交易价格(在price_type ='TRADE时为收盘价)。

This is what I have: 这就是我所拥有的:

SELECT b.price_timestamp, b.security, b.close AS bid, t.close AS trade
  FROM stock b
  FULL OUTER JOIN stock t
    ON b.price_timestamp = t.price_timestamp
   AND b.security = t.security
 WHERE b.price_type = 'BID'
   AND t.price_type = 'TRADE'

This returns 19370 records. 这将返回19370条记录。 There are 40147 bid prices, 19399 trade prices, so I'm expecting at least max(40147, 19399) = 40147 records. 有40147个买入价,19399个交易价,所以我希望至少有max(40147,19399)= 40147条记录。 At a glance, it looks it's returning an INNER JOIN. 乍一看,它似乎正在返回INNER JOIN。

I've also tried moving "b.security = t.security" in the ON cluse to the WHERE clause -- no luck. 我还尝试过将ON子句中的“ b.security = t.security”移到WHERE子句-运气不好。

You're getting fewer records because on the where clause you're referring both aliases 'b'& 't'. 您得到的记录更少,因为在where子句中您同时引用了两个别名“ b”和“ t”。 So, it is filtering only those joined records where b.price_type = 'BID' and t.price_type = 'TRADE' 因此,它仅过滤b.price_type ='BID'和t.price_type ='TRADE'的那些联接记录。

Try moving the where conditions into the joins 尝试将where条件移动到联接中

For example: 例如:

SELECT b.price_timestamp, b.security, b.close AS bid, t.close AS trade
  FROM stock b
  FULL OUTER JOIN stock t
    ON b.price_timestamp = t.price_timestamp
   AND b.security = t.security
   AND t.price_type = 'TRADE'
 WHERE b.price_type = 'BID'

This would return all records from alias 'b' where b.price_type = 'BID', and at least one record from alias 't'. 这将从别名“ b”(其中b.price_type =“ BID”)返回所有记录,并至少返回别名“ t”的一条记录。 If no matching records are found from 't', a null records will be returned. 如果从“ t”中找不到匹配的记录,则将返回空记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM