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
Two columns in subquery in where clause
提问by robson
I have a query:
我有一个疑问:
SELECT s.period, s.year, s.amount
FROM salaries s
I would like to select from salaries
table 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 IN
condition:
您可以对一个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 exists
solution 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)