在SQL Server 2008中,如何使用新的魔术列(位值)从table1中检索数据,这个新列采用了真正的'如果来自table1的当前id存在于table2中,则采用' false'。
例如:
表1
id | name
-----------
10 | USA
11 | UK
12 | France
表2
id | title | fk
----------------------
1 | v1 | 10
2 | v2 | 10
3 | v3 | 11
结果:
id | name | new column
----------------------------
10 | USA | true
11 | UK | true
12 | France | false
答案 0 :(得分:0)
SELECT DISTINCT table1.id, table1.name,
CASE WHEN table2.id IS NULL THEN 'False' ELSE 'True' END AS mycolumn
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.fk
答案 1 :(得分:0)
了解不同的联接类型。这是基本的SQL。
SELECT Table1.[id], [name], CASE WHEN Table2.[id] IS NULL THEN 0 ELSE 1 END As [New column]
FROM Table1 LEFT JOIN
Table2 ON(Table1.[id] = Table2.[fk])
答案 2 :(得分:0)
以下查询返回预期结果:
SELECT T1.*
,CAST(CASE
WHEN T2.id IS NOT NULL THEN 1
ELSE 0
END AS BIT) AS magic_column
FROM table1 T1
LEFT JOIN table2 T2 ON T1.id = T2.fk
答案 3 :(得分:0)
您可以使用左连接来获取所需的数据。
<强> SQL 强>
select A.*
,case when B.fk is not null then 'true' else 'false' end as [new column]
from table1 A
left join
(
select distinct fk from table2
)B on A.id=B.fk
<强>输出强>
id name new column
10 USA true
11 UK true
12 France false