需求:「找出 title 與 address 同時相同的電影明星配對」。直覺用 <> 會產生鏡像重複(A-B、B-A),本文示範用 < 巧妙去重。
movestarid | name | title | address ---|-----------|-----------------|---------- 1 | 成龍 | 動作巨星 | 香港 2 | 李連傑 | 動作巨星 | 香港 3 | 周星馳 | 喜劇之王 | 香港 4 | 劉德華 | 天王巨星 | 香港
SELECT star1.name AS name1,
star2.name AS name2,
star1.title,
star1.address
FROM movestar AS star1
JOIN movestar AS star2
ON star1.title = star2.title
AND star1.address = star2.address
AND star1.name < star2.name; -- 關鍵:字典序去重
name1 | name2 | title | address ------|-------|----------|-------- 成龍 | 李連傑 | 動作巨星 | 香港
star1.name < star2.name:利用字串大小比較,只保留「名字較小」在前的組合,自動排除 (李連傑, 成龍) 以及 (成龍, 成龍) 這類自配對。<>,會產生 雙向重複 與 自我配對,資料筆數暴增 2~3 倍。SELECT title, address, COUNT(*) AS dup_cnt,
STRING_AGG(name, ', ') AS names -- SQL Server 2017+ / PostgreSQL
FROM movestar
GROUP BY title, address
HAVING COUNT(*) > 1;
現代資料庫建議直接用 GROUP BY ... HAVING COUNT(*) > 1 配合字串聚合函數,語意更清晰、效能更佳。