postgresql 在两列上加入 postgres 表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17466663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:16:15  来源:igfitidea点击:

Join postgres table on two columns?

postgresql

提问by coderama

I can't find a straightforward answer. My query is spitting out the wrong result, and I think it's because it's not seeing the "AND" as an actual join.

我找不到直接的答案。我的查询吐出错误的结果,我认为这是因为它没有将“AND”视为实际连接。

Can you do something like this and if not, what is the correct approach:

你能做这样的事情吗,如果不能,正确的方法是什么:

SELECT * from X
LEFT JOIN Y
ON
  y.date = x.date AND y.code = x.code

?

?

采纳答案by coderama

This is possible:

这个有可能:

The ON clause is the most general kind of join condition: it takes a Boolean value expression of the same kind as is used in a WHERE clause. A pair of rows from T1 and T2 match if the ON expression evaluates to true for them.

ON 子句是最通用的一种连接条件:它采用与 WHERE 子句中使用的类型相同的布尔值表达式。如果 ON 表达式对它们的计算结果为真,则来自 T1 和 T2 的一对行匹配。

http://www.postgresql.org/docs/9.1/static/queries-table-expressions.html#QUERIES-FROM

http://www.postgresql.org/docs/9.1/static/queries-table-expressions.html#QUERIES-FROM

Your SQL looks OK.

您的 SQL 看起来不错。

回答by Bohemian

It's fine. In fact, you can put anycondition in the ON clause, even one not related to the key columns or even the the tables at all, eg:

没关系。事实上,您可以在 ON 子句中放置任何条件,甚至是与键列甚至表根本不相关的条件,例如:

SELECT * from X
LEFT JOIN Y
    ON y.date = x.date
    AND y.code = x.code
    AND EXTRACT (dow from current_date) = 1