这是我的测试用例
CREATE TABLE matches AS
SELECT 1 s, 2 d
UNION SELECT 1, 3 -- (1,2) preferred
UNION SELECT 2, 2 -- (1,2) preferred
UNION SELECT 2, 3
UNION SELECT 3, 3 -- (2,3) preferred
UNION SELECT 3, 4;
我想过滤该表,并仅将每个s或d值保留一次,优先处理最小(s,d)对。结果应为(1,2),(2,3),(3,4)
。
如何有效地做到这一点?
我尝试了以下查询,但仅在与不同s值相关联的d值不重叠时才有效
SELECT * FROM (
SELECT
*,
row_number() OVER (PARTITION BY s ORDER BY d) rs,
row_number() OVER (PARTITION BY d ORDER BY s) rd
FROM matches
) t
WHERE rd = rs;
任何帮助将不胜感激。
答案 0 :(得分:0)
如果我正确地解释了您的意图,则可以通过将表复制到在s
和d
上具有UNIQUE索引的新(可能是临时的)表中并使用{{1} }复制数据:
INSERT IGNORE
输出:
CREATE TABLE matches AS
SELECT 1 s, 2 d
UNION SELECT 1, 3 -- (1,2) preferred
UNION SELECT 2, 2 -- (1,2) preferred
UNION SELECT 2, 3
UNION SELECT 3, 3
UNION SELECT 3, 4;
CREATE TABLE matches2 (s INT, d INT);
ALTER TABLE matches2 ADD UNIQUE KEY (s), ADD UNIQUE KEY(d);
INSERT IGNORE INTO matches2
SELECT * FROM matches ORDER BY s, d;
SELECT * FROM matches2