我有父/子表:
父表:
1 |亚历山德拉 2 |纳塔利娅
子表:
1 | 1 |程序员 2 | 1 |手术 3 | 2 |程序员 4 | 2 | IT
如何根据过滤器返回记录集,例如,如果我们想要使用“Programmer”获取我们想要设置的所有记录:
回复表:
1 | 1 | Programmer
2 | 3 | Programmer
但是如果过滤器看起来像:“Programmer”和“Surgery”,则查询必须仅返回:
回复表:
1 | 1 | Programmer
1 | 2 | Surgery
正如您所看到的,我还需要某种“连接”才能在子表中“连接”描述和代码。
提前致谢。
答案 0 :(得分:1)
SELECT t.id_parent,
t.id,
t.description
FROM CHILD t
JOIN CHILD p ON p.id_parent = t.id_parent AND p.description = 'Programmer'
JOIN CHILD s ON s.id_parent = t.id_parent AND s.description = 'Surgery'
根据您的SQL,您需要使用:
SELECT p.ID,
c.ID,
c.ID_SpecMatrix
FROM Parent p
JOIN Child c ON p.ID = c.ID_Parent AND c.ID_SpecMatrix = 4
JOIN Child c2 ON p.ID = c2.ID_Parent AND c2.ID_SpecMatrix = 5
GROUP BY p.ID,
c.ID,
c.ID_SpecMatrix
关键是加入CHILD表的其他副本。 ID_parent
到ID将记录链接在一起; AND过滤CHILD表的副本,使其仅包含ID_SpecMatrix
符合条件的行。
查询需要使用动态SQL扩展到您想要使用的许多条件。
答案 1 :(得分:0)
选择* 来自父母p 左加入孩子c 在p.id = c.id_parent上 其中c.description ='程序员' 或c.description ='Surgen'
答案 2 :(得分:0)
这个怎么样
SELECT * FROM Child
WHERE id_specmatrix IN (4,5) AND
Parent_ID IN (SELECT DISTINCT parent.id FROM parent p
JOIN Child s1 ON s1.id_parent = p.id AND s1.id_specmatrix = 4
JOIN Child s2 ON s2.id_parent = p.id AND s2.id_specmatrix = 5)