简体   繁体   English

PostgreSQL:多列精确匹配

[英]PostgreSQL: Exact Match on Multiple Columns

Background背景

I have a table that contains multiple ID fields like so:我有一个包含多个 ID 字段的表,如下所示:

work_id TEXT DEFAULT NULL,
card_id TEXT DEFAULT NULL,
employee_id TEXT DEFAULT NULL,
school_id TEXT DEFAULT NULL

Find exact matches查找完全匹配

And I need to find the rows where all of these fields match exactly.我需要找到所有这些字段完全匹配的行。 My initial syntax for this comparison would be:我进行此比较的初始语法是:

SELECT * FROM table
WHERE
  work_id = card_id AND
  work_id = employee_id AND
  work_id = school_id;

Find any non-matching rows查找任何不匹配的行

Conversely, I also need to find the rows where all of these fields do not match exactly.相反,我还需要找到所有这些字段不完全匹配的行。 My initial syntax for this comparison would be:我进行此比较的初始语法是:

SELECT * FROM table
WHERE
  work_id NOT = card_id OR
  work_id NOT = employee_id OR
  work_id NOT = school_id;

Question问题

Is there an easier way to do this comparison across more than two columns at a time?有没有一种更简单的方法可以一次跨两列以上进行比较? Is there some sort of array operator that will find matching or non-matching values across multiple columns?是否有某种数组运算符可以跨多列查找匹配或不匹配的值?

Future-Proofing the Code面向未来的代码

I ask this because if the number of columns being compared is high, this type of code could prove unwieldly and hard to maintain down the road.我问这个是因为如果要比较的列数很高,这种类型的代码可能会变得笨拙且难以维护。 For example, if later on, we add another ID column to the table, I would need to manually add a new line to the comparison logic to include the new column.例如,如果稍后我们向表中添加另一个 ID 列,我需要手动向比较逻辑添加新行以包含新列。

You can use ANY or ALL with an array您可以将 ANY 或 ALL 与数组一起使用

SELECT * 
FROM the_table
WHERE work_id = all (array[card_id, employee_id, school_id])


SELECT * 
FROM the_table
WHERE work_id <> any (array[card_id, employee_id, school_id])

You could use composite values:您可以使用复合值:

WHERE (work_id, work_id, work_id) <>
      (card_id, employee_id, school_id)

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

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