postgresql where 子句中的子查询中的两列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29255010/
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-10-21 01:50:05  来源:igfitidea点击:

Two columns in subquery in where clause

sqlpostgresql

提问by robson

I have a query:

我有一个疑问:

SELECT s.period, s.year, s.amount 
FROM salaries s

I would like to select from salariestable only the rows that have period and year equal to:

我只想从salaries表中选择期间和年份等于的行:

SELECT p.period, p.years 
FROM periods p

I know that the simplest way would be use join, but the problem is - that in the application I can add only a clause after WHERE

我知道最简单的方法是使用 join,但问题是 - 在应用程序中我只能在后面添加一个子句 WHERE

So the solution should be:

所以解决办法应该是:

SELECT s.period, s.year, s.amount 
FROM salaries s 
WHERE ...

Is that possible?

那可能吗?

EDIT:The result should be the same as:

编辑:结果应该与:

SELECT s.period, s.year, s.amount 
FROM salaries s
  JOIN periods p ON s.period = p.period AND s.year = p.year

回答by a_horse_with_no_name

You can use more than one column for an INcondition:

您可以对一个IN条件使用多个列:

SELECT s.period, s.year, s.amount 
FROM salaries s
where (s.year, s.period) in (select year, period from periods)

But Gordon's not existssolution is probably faster.

但戈登的not exists解决方案可能更快。

回答by Gordon Linoff

Does this work with your environment?

这适用于您的环境吗?

WHERE EXISTS (SELECT 1
              FROM periods p
              WHERE p.period = s.period AND p.year = s.year
             )

回答by Rahul Tripathi

Try this:

试试这个:

SELECT s.period, s.year, s.amount FROM salaries s
where s.period in (select period from periods)
and s.year in (select year from periods)