简体   繁体   中英

PostgreSQL: Exact Match on Multiple Columns

Background

I have a table that contains multiple ID fields like so:

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.

You can use ANY or ALL with an array

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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