2016-03-16 62 views
3

我有两个配置表。该结构如下:加入两个表并获取值

Table 1: Client_Config 
id, name, value, type, description 

Table 2: App_Config 
name, value, type, description 

我想从Client_configwhere id = @id得到namevalue

我也想从App_config得到namevalues对于在client_config没有条目(与名称匹配)的行。两个表中相同名称的值可能不同。

如: 价值观Client_Config在APP_CONFIG

testName, testValue1, testType, testDescription 
testName1, testValue1, testType1, testDescription1 
testName2, testValue2, testType2, testDescription2 
testName3, testValue3, testType3, testDescription3 

在结果集我需要以下行

1, testName, testValue, testType, testDescription 
1, testName1, testValue1, testType1, testDescription1 
1, testName2, testValue2, testType2, testDescription2 

值:

1, testName, testValue, testType, testDescription 
1, testName1, testValue1, testType1, testDescription1 
1, testName2, testValue2, testType2, testDescription2 
NULL, testName3, testValue3, testType3, testDescription3 

回答

2

你可以它采用了一块左侧做加盟:

SELECT t.id, s.name, s.value, s.type, s.description 
FROM App_Config s 
LEFT JOIN Client_Config t 
ON(t.name = s.name and t.id = @id) 
1

您可以使用做UNION ALL作业:

DECLARE @id INT = 1 

SELECT id, name, value, type, description 
FROM Client_Config 
WHERE id = @id 

UNION ALL 

SELECT NULL, name, value, type, description 
FROM App_Config AS ac 
WHERE NOT EXISTS (SELECT 1 
        FROM Client_Config AS cc 
        WHERE cc.name = ac.name AND cc.id = @id) 

Demo here

3

您可以尝试像下面

select 
    c.id, a.name, a.value, a.type, a.description 
from App_Config a 
left join 
(
select * from Client_Config where [email protected] 
)c 
on c.name=a.name 

说明查询:我们需要app_config所有行和来自client_config相应的ID。所以,我们做的从A到**LEFT JOIN** C的C测试结果设定。但是必须包含特定@id行只有如此,我们偷偷在WHERE条款在C组

的Sql小提琴演示链接:http://sqlfiddle.com/#!6/44659/4

1

与左加入你得到所有左表中的行与右表中的所有相应的行。如果没有匹配的信息,则右表的列将为NULL。 看看这个有用的图: SQL Join Diagrams

特别是,你的查询可以是这样的:

SELECT c.id, a.name, a.value, a.type, a.description 
FROM App_Config a 
LEFT JOIN Client_Config c 
ON c.name = a.name 
WHERE c.id = @id