我有两个表T1和T2,其中包含以下列 -
T1
Project_ID
Category
Column_X
Column_Y
Column_Z
T2
Proj_ID
Category
Parent_Project_ID
我想编写一个查询来从T1获取具有以下条件的记录 -
我不确定如何仅在结果出现在第一个条件下时检查第二个条件。
需要什么?
按要求添加样本数据和所需结果 -
答案 0 :(得分:1)
SELECT * FROM T2 WHERE T2.Proj_ID IN ( SELECT Project_ID FROM T1 WHERE Category = 'A' )
这应该完成所需的工作。
SELECT * from T2 as d
WHERE EXISTS ( SELECT * from T1 as d1 where d1.Category = 'A' and d1.Project_ID = d.Proj_ID )
SELECT * from T1 as d1 right join T2 as d2 on d1.Project_ID = d2.Proj_ID
WHERE d1.CodTert = 500
我做了一个更新,这些查询给出了相同的结果,一个使用了JOIN而没有。
答案 1 :(得分:1)
我假设T2
。Parent_Project_ID
和T1
。Project_ID
是相关的。如果是这样,你可以使用它:
Select T3.*
From T1
Join T2 On T2.Parent_Project_ID = T1.Project_ID
Join T1 T3 On T3.Project_ID = T2.Proj_ID
Where T1.Category = 'A'
这将只获得具有“A”类别的项目的子项目。
答案 2 :(得分:1)
修改强>:
根据已添加到问题的输出格式,以下使用LEFT OUTER JOIN
的查询将呈现所需的确切结果:
SELECT
T2.PROJ_ID Project_ID,
T2.Category,
T1.Column_X,
T1.Column_Y,
T1.Column_Z,
T2.Parent_Project_ID
FROM T1 T1_PARENTS
INNER JOIN T2
ON T2.Parent_Project_ID = T1.Project_ID and T1.Category = 'A'
INNER JOIN T2 T2_CHILDREN
ON T2_CHILDREN.PROJ_ID = T2.Parent_Project_ID OR T2_CHILDREN.Parent_Project_ID = T2.Parent_Project_ID
LEFT OUTER JOIN T1
ON T2_CHILDREN.PROJ_ID = T1.Project_ID;
答案 3 :(得分:1)
要获取第二个表中的所有记录,您可以使用以下查询。
SELECT
t2.*
FROM T1 t1
RIGHT OUTER JOIN T2 t2 ON t1.Project_ID = t2.Project_ID
WHERE t1.Category = "A"