[英]Find all linked records using self join
我有這張表,我正在嘗試使用自聯接。 我只能達到預期結果的 50%。
create table auto_correct(spell varchar(255), ne varchar(255));
insert into auto_correct values ('test', 'testing');
insert into auto_correct values ('adn', 'and');
insert into auto_correct values ('and', 'andru');
insert into auto_correct values ('testing', 'tested');
insert into auto_correct values ('this', 'that');
insert into auto_correct values ('junk', 'delete');
拼寫 | ne |
---|---|
測試 | 測試 |
廣告 | 和 |
和 | 安德魯 |
測試 | 測試 |
這 | 那 |
垃圾 | 刪除 |
單詞“test”通過“testing”鏈接到“tested” 單詞“adn”通過“and”鏈接到“andru” 如何找到所有此類鏈接記錄並與非鏈接行一起顯示?
預期的結果是:
拼寫 | ne |
---|---|
測試 | 測試 |
廣告 | 安德魯 |
這 | 那 |
垃圾 | 刪除 |
我試過這個:
select b.spell, a.ne
from auto_correct as a
left join auto_correct as b on a.spell = b.ne
where b.spell is not null;
返回:
廣告 | 安德魯 |
---|---|
測試 | 測試 |
上述輸出中缺少未找到匹配項的其余記錄。
WITH RECURSIVE
cte AS ( SELECT *
FROM auto_correct
WHERE NOT EXISTS ( SELECT NULL
FROM auto_correct ac
WHERE auto_correct.spell = ac.ne )
UNION ALL
SELECT cte.spell, auto_correct.ne
FROM cte
JOIN auto_correct ON cte.ne = auto_correct.spell )
SELECT *
FROM cte
WHERE NOT EXISTS ( SELECT NULL
FROM auto_correct
WHERE auto_correct.spell = cte.ne )
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e90235ce5dde96a7255f8afe1a19d334
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.