SQL Query根据现有列值获取记录

时间:2018-01-24 11:53:44

标签: sql-server

我想编写SQL查询来检索以下数据。

enter image description here

表1 - > ID_1 / ID_2由Table2的主键

组成

基于此预期结果需要Value1&值2。 在代码级别,我从表1和表1中检索信息。通过迭代执行另一个查询来获取Value1 / Value2的记录。

我想编写SQL查询以一次性获取整个数据。

3 个答案:

答案 0 :(得分:1)

您可以在两个id列上将table_1与表2连接两次:

select t1.*, 
    t2_1.value as value1,
    t2_2.value as value2
from table_1 t1
join table t2_1 on t1.id_1 = t2_1.id
join table t2_2 on t1.id_2 = t2_2.id;

如果table_1中的任何id列可以为空,请将内部联接更改为left。类似的东西:

select t1.*, 
    t2_1.value as value1,
    t2_2.value as value2
from table_1 t1
left join table t2_1 on t1.id_1 = t2_1.id
left join table t2_2 on t1.id_2 = t2_2.id;

答案 1 :(得分:1)

试试这个工作示例:

DECLARE @Table1 TABLE([User] VARCHAR(100),Data VARCHAR(100),ID_1 INT,ID_2 INT);
INSERT INTO @Table1 VALUES('Admin','data',1,2)
                         ,('test','data',3,2) 

DECLARE @Table2 TABLE(ID INT,Value VARCHAR(100));
INSERT INTO @Table2 VALUES(1,'ABC')
                         ,(2,'PQR')
                         ,(3,'XYZ');  
SELECT t1.[User]
      ,t1.Data
      ,t1.ID_1
      ,t2a.Value
      ,t1.ID_2
      ,t2b.Value
FROM @Table1 AS t1
LEFT JOIN @Table2 AS t2a ON t1.ID_1=t2a.ID
LEFT JOIN @Table2 AS t2b ON t1.ID_2=t2b.ID

结果

User    Data    ID_1    Value   ID_2    Value
Admin   data    1       ABC     2       PQR
test    data    3       XYZ     2       PQR

答案 2 :(得分:0)

你只需要加入Table2两次

SELECT
    T1.[User],
    T1.[Data],
    T1.ID_1,
    Value1 = T2.Value,
    T1.ID_2,
    Value2 = T3.Value
    FROM Table1 T1
       INNER JOIN Table2 T2
          ON T1.ID_1 = T2.ID
       INNER JOIN Table2 T3
          ON T1.ID_2 = T3.ID