CREATE TABLE #C (cid int, id int,value varchar(2))
INSERT #C SELECT 1, 1,'a'
UNION ALL SELECT 2, 1,'d'
UNION ALL SELECT 3, 2,'a'
UNION ALL SELECT 4, 2,'b'
UNION ALL SELECT 5, 3,'c'
CREATE TABLE #A (id int, name varchar(2),age int)
INSERT #A SELECT 1, 'de',33
UNION ALL SELECT 2, 'ac',34
UNION ALL SELECT 3, 'ea',35
-- 查询处理
SELECT #A.*,T1.cid,T1.value FROM #A INNER JOIN (
SELECT *
FROM(
SELECT DISTINCT
id
FROM #C
)A
OUTER APPLY(
SELECT
[cid]= STUFF(REPLACE(REPLACE(
(
SELECT cid FROM #C N
WHERE id = A.id
FOR XML AUTO
), '', ''), 1, 1, '')
)N
OUTER APPLY(
SELECT
[value]= STUFF(REPLACE(REPLACE(
(
SELECT value FROM #C N
WHERE id = A.id
FOR XML AUTO
), '', ''), 1, 1, '')
)d
)T1 ON #A.id=T1.id
DROP TABLE #A
drop table #C
-------------------------
id name age cid value
1 de 33 1,2 a,d
2 ac 34 3,4 a,b
3 ea 35 5 c
select a.id, a.name, a.age, wm_concat(c.cid) cid, wm_concat(c.value) value
from a
left join c
on a.id = c.id
group by a.id, a.name, a.age
数据插入
insert into b(aid,bvalue) select 3,'bvalue' from a where a.id=3
解释:select 3,'bvalue' from a where a.id=3
3=我们向B表中插入的aid的值
bvalue=我们向B表中插入的bvalue的值
使用where
语句判断主表(A表)是否拥有ID为3的数据
数据查询
select a.avalue,b.aid ,b.bvalue
from a left join b on b.aid=a.id
SELECT
t1.id,t2.id,t3.id
FROM t1,( t2 LEFT JOIN t3 ON (t3.id=t1.id) )
WHERE
t1.id=t2.id;