SQL記錄篩選 語句怎樣寫
CREATE TABLE T1(
T1DH VARCHAR(10),
PH VARCHAR(20),
SL Numeric(9,4) )
CREATE TABLE T2(
T2DH VARCHAR(10),
PH VARCHAR(20),
SL Numeric(9,4) )
INSERT INTO T1
SELECT 'T1A1 ', 'A ', '10 '
UNION ALL
SELECT 'T1A1 ', 'B ', '5 '
UNION ALL
SELECT 'T1A2 ', 'B ', '5 '
UNION ALL
SELECT 'T1A2 ', 'C ', '5 '
INSERT INTO T2
SELECT 'T2A1 ', 'A ', '10 '
UNION ALL
SELECT 'T2A1 ', 'B ', '5 '
UNION ALL
SELECT 'T2A1 ', 'C ', '5 '
UNION ALL
SELECT 'T2A2 ', 'B ', '5 '
UNION ALL
SELECT 'T2A2 ', 'C ', '5 '
SELECT * FROM T1
SELECT * FROM T2
如何將 T2中的 'T2A1 ' , 'C ', '5 ' 通過一條語句插入到T1中
insert INTO t1(T1DH,PH,SL)
SELECT T1.T1DH,T2.PH,T2.SL
FROM T2,T1
WHERE T2DH= 'T2A1 ' AND T1DH= 'T1A1 ' AND NOT EXISTS(SELECT * FROM T1,T2 WHERE T1DH= 'T1A1 ' AND T2DH= 'T2A1 ' AND T1.PH=T2.PH)
使t1中增加一條 'T1A1 ', 'C ', '5 '的記錄?
[解决办法]
insert T1
select * from T2 as tmp
where T2DH= 'T2A1 ' and not exists
(select 1 from T1 where T1DH= 'T1A1 ' and PH=tmp.PH)
select * from T1
--result
T1DH PH SL
---------- -------------------- -----------
T1A1 A 10.0000
T1A1 B 5.0000
T1A2 B 5.0000
T1A2 C 5.0000
T2A1 C 5.0000
(5 row(s) affected)
[解决办法]
marco08(天道酬勤)
感謝你的回復,確實是高手。