请教SQL查询关联表中是否有数据。
Table1
ID Name
1 张三
2 李四
3 王二
Table2
ID Product
1 电脑
3 鼠标
1 手机
查询Table1时同时查询Table2中是否有相同ID记录,如有置1,没有置0
需要结果如下:
ID Name Yes
1 张三 1
2 李四 0
3 王二 1
[最优解释]
select id ,name,case when Product is null 0 else 1 end as YES Table1 left join Table2 on Table1.ID=Table2.ID
[其他解释]
CREATE TABLE #temp (id INT,NAME VARCHAR(50))
INSERT INTO #temp VALUES(1,'A')
INSERT INTO #temp VALUES(2,'B')
INSERT INTO #temp VALUES(3,'C')
CREATE TABLE #temp2 (id INT,Product VARCHAR(50))
INSERT INTO #temp2 VALUES(1,'X')
INSERT INTO #temp2 VALUES(2,'Y')
INSERT INTO #temp2 VALUES(1,'X')
SELECT #temp.id ,
NAME ,
CASE WHEN ( COUNT(Product) > 1 ) THEN 1
ELSE 0
END AS YES
FROM #temp
INNER JOIN #temp2 ON #temp.id = #temp2.id
GROUP BY #temp.id ,NAME
idNAMEYES
1A1
2B0
SELECT *,1 yes
FROM table1 a
WHERE EXISTS (SELECT 1 FROM table2 b WHERE a.id=B.id)
UNION ALL
SELECT *,0 yes
FROM table1 a
WHERE NOT EXISTS (SELECT 1 FROM table2 b WHERE a.id=B.id)