[英]Selecting from a Database based on a list of unique pairs
For Example if I am given the following table 例如,如果给出下表
Id Key Value
1 A Alpha
2 B Alpha
3 A Charlie
And I took the input {(A, Charlie) and (B, Alpha)} and I asked to return all the IDs I would want it to return 2 and 3 but NOT 1. 我接受了输入{(A,Charlie)和(B,Alpha)}并且我要求返回我希望它返回2和3但不是1的所有ID。
What is the best way to do this? 做这个的最好方式是什么? Can I combine it all into one query, (for speed) or would I have to run a repeat query for each value pair I received.
我可以将它全部合并到一个查询中(为了速度)还是我必须为我收到的每个值对运行重复查询。
I think Postgresql has the most elegant solution: 我认为Postgresql有最优雅的解决方案:
SELECT *
FROM T
WHERE ("Key", "Value") IN (('B', 'Alpha'), ('A', 'Charlie'));
In SQL-SERVER 2008 and onward you can use VALUES
to build your tuples: 在SQL-SERVER 2008及更高版本中,您可以使用
VALUES
来构建元组:
SELECT T.*
FROM T
INNER JOIN
( VALUES
('B', 'Alpha'),
('A', 'Charlie')
) v (Key, Value)
ON v.Key = T.Key
AND v.Value = T.Value
Or for a procedure you could create a key-value pair type and pass this as a parameter: 或者对于过程,您可以创建键值对类型并将其作为参数传递:
CREATE TYPE KeyValuePair AS TABLE ([Key] VARCHAR(1), [Value] VARCHAR(7));
DECLARE @T AS KeyValuePair
INSERT @T
VALUES
('B', 'Alpha'),
('A', 'Charlie')
SELECT T.*
FROM T
INNER JOIN @T v
ON v.[Key] = T.[Key]
AND v.Value = T.Value;
For MySQL I think you may have to just build this using AND/OR
对于MySQL,我认为您可能必须使用
AND/OR
来构建它
SELECT *
FROM T
WHERE (`Key` = 'A' AND `Value` = 'Charlie')
OR (`Key` = 'B' AND `Value` = 'Alpha')
Example on SQL Fiddle 关于SQL小提琴的例子
My Knowledge of other DBMS is limited, so if it is not one of the above sorry I can't be of more help. 我对其他DBMS的了解是有限的,所以如果它不是上述抱歉之一,我无法提供更多帮助。
EDIT (With the help of a_horse_with_no_name ) 编辑(在a_horse_with_no_name的帮助下)
The PostgreSQL syntax also works for Oracle (and I think DB2) PostgreSQL语法也适用于Oracle (我认为DB2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.