按多列结果搜索

时间:2018-07-16 06:39:03

标签: sql sql-server sql-server-2014

使用这种查询的正确方法是什么?

 SELECT Project_name,
  FROM [Table 1]
  WHERE Project_id in
      (SELECT ID_1, ID_2, ID_3, ID_4, ID_5
       FROM [Table 2])

即按2列或更多列的选择结果进行搜索

3 个答案:

答案 0 :(得分:3)

使用apply

  SELECT Project_name,
  FROM [Table 1]
  WHERE Project_id in
  (SELECT v.value FROM [Table 2]
   cross apply (values(ID_1), 
                      (ID_2), 
                      (ID_3), 
                      (ID_4), 
                      (ID_5))v(value))

答案 1 :(得分:2)

根据您的问题,您可以尝试使用exists代替in

如果该查询没有达到您的期望。

您能否提供一些示例数据,预期结果,对问题的更多解释就可以弄清楚了。

SELECT Project_name,
FROM [Table 1]
WHERE exists
(
select 1 FROM [Table 2]
WHERE Project_id = ID_1 or 
      Project_id = ID_2 or
      Project_id = ID_3 or
      Project_id = ID_4 or
      Project_id = ID_5 
)

答案 2 :(得分:0)

我建议在第二张桌子上使用Unpivot。

架构:

CREATE TABLE #PROJECTS(ID INT IDENTITY,NAME VARCHAR(10))
INSERT INTO #PROJECTS
VALUES('A'),('B'),('C'),('D'),('E'),('F'),('G')

CREATE TABLE #PROJECT_DETAIL(ID INT IDENTITY, P1 INT,P2 INT,P3 INT )
INSERT INTO #PROJECT_DETAIL
VALUES(1,4,5),(2,5,2),(3,1,4)

现在请取消透视#PROJECT_DETAIL,并在IN运算符中使用未透视ID列。

SELECT * FROM #PROJECTS
WHERE ID IN (
SELECT PROJECT_IDS FROM #PROJECT_DETAIL
UNPIVOT
(
    PROJECT_IDS FOR PROJECTS IN ([P1],[P2],[P3])
)UP
)

结果:

ID  NAME
1   A
2   B
3   C
4   D
5   E