江户川乱折腾
考虑以下...DROP TABLE IF EXISTS my_table;CREATE TABLE my_table(transaction_id SERIAL PRIMARY KEY,vendor_id INT NOT NULL,currency CHAR(3) NOT NULL);INSERT INTO my_table VALUES(1101,201,'USD'),(1102,202,'EUR'),(1103,203,'CHF'),(1104,202,'EUR'),(1105,204,'HUF'),(1106,202,'USD'),(1107,204,'USD');SELECT a.* FROM my_table a LEFT JOIN ( SELECT x.* FROM my_table x JOIN ( SELECT MIN(transaction_id) transaction_id FROM my_table GROUP BY vendor_id ) y ON y.transaction_id = x.transaction_id ) b ON b.vendor_id = a.vendor_id AND b.currency = a.currency WHERE b.transaction_id IS NULL; +----------------+-----------+----------+ | transaction_id | vendor_id | currency | +----------------+-----------+----------+ | 1106 | 202 | USD | | 1107 | 204 | USD | +----------------+-----------+----------+ 要了解这里发生了什么,只需将查询分解为其组成部分并添加b.transaction_id到 SELECT...离开'y'SELECT MIN(transaction_id) transaction_id FROM my_table GROUP BY vendor_id该位获取每个供应商的第一个 transaction_id。这是有效的,因为 transaction_id 是 PRIMARY KEY。然后我们将此结果连接回源表,以获取与该 transaction_id 对应的其他列(具体currency而言,在这种情况下): SELECT x.* FROM my_table x JOIN ( SELECT MIN(transaction_id) transaction_id FROM my_table GROUP BY vendor_id ) y ON y.transaction_id = x.transaction_id最后,我们再次将上述所有内容进行 OUTER JOIN 回表,以获取不满足条件的行 ( b.vendor_id = a.vendor_id AND b.currency = a.currency WHERE b.transaction_id IS NULL)。SELECT a.* , b.transaction_id FROM my_table a LEFT JOIN ( SELECT x.* FROM my_table x JOIN ( SELECT MIN(transaction_id) transaction_id FROM my_table GROUP BY vendor_id ) y ON y.transaction_id = x.transaction_id ) b ON b.vendor_id = a.vendor_id AND b.currency = a.currency;+----------------+-----------+----------+----------------+| transaction_id | vendor_id | currency | transaction_id |+----------------+-----------+----------+----------------+| 1101 | 201 | USD | 1101 || 1102 | 202 | EUR | 1102 || 1103 | 203 | CHF | 1103 || 1104 | 202 | EUR | 1102 || 1105 | 204 | HUF | 1105 || 1106 | 202 | USD | NULL | <-- We only want| 1107 | 204 | USD | NULL | <-- these 'NULL' rows+----------------+-----------+----------+----------------+