场合:
我有一个名为“word”的表,其中包含一个带有相关翻译的单词。
| ID | name | lang_id | parent_id |
|----|----------|---------|-----------|
| 1 | screw | 1 | null |
| 2 | schraube | 2 | 1 |
| 3 | vis | 3 | 1 |
所以螺丝是没有父母的主要词汇。其他数据集与父节点的父节点关联。
我想要的是什么:
我需要一个查询,显示我搜索的单词和我输入的单词。
我尝试了什么:
select word.id, word.name, word.lang_id, word.parent_id
from word
left join word w2 on word.parent_id = w2.parent_id
WHERE w2.name = 'screw';
-- and word.lang_id = 2
不幸的是,结果不包含我键入的单词。此外,它还显示所有数据集,而不仅仅是具有特定语言的数据集。
答案 0 :(得分:0)
您可以修改以下查询以获得答案。
DECLARE @FromLanguageId SMALLINT = 2; --german
DECLARE @ToLanguageId SMALLINT = 3; --french
DECLARE @NAME NVARCHAR(300) = 'schraube';
--DECLARE @FromLanguageId SMALLINT = 1; --english
--DECLARE @ToLanguageId SMALLINT = 3; --french
--DECLARE @NAME NVARCHAR(300) = 'screw';
--Get the mathing record
;
WITH ctematch
AS (
--gets the matching record (child or parent)
SELECT match.*
FROM [word] match
WHERE match.NAME LIKE @NAME),
--Join its sibling , parent and childs
ctefamilydata
AS (SELECT *
FROM ctematch match
UNION
--Parent
SELECT parent.*
FROM ctematch match
INNER JOIN [word] parent
ON match.[parent_id] = parent.[id]
UNION
--Child
SELECT child.*
FROM ctematch match
INNER JOIN [word] child
ON child.[parent_id] = match.[id]
UNION
--Siblings
SELECT siblings.*
FROM ctematch match
INNER JOIN [word] siblings
ON match.[parent_id] = siblings.[parent_id])
--Filter and get the data
SELECT *
FROM ctefamilydata Cte
WHERE Cte.[lang_id] = @ToLanguageId
OR Cte.[lang_id] = @FromLanguageId