复制数据库中的所有单行 table
Duplicate All single rows in database table
我有这个 table 有多列。主键是 (type,ref,code)
,行类型为 t1
,t2
,有两种状态有效 (V)
和无效 (I)
。
状态 t1
中的每个无效行都应该在状态 t2
中有一个有效行,
但是我的 table 已经有一些状态为无效的行,这些行在状态 t2
.
中没有有效行
示例:
type | ref | code | state .....
----------------------------------------
t1 | 1 | c1 | V
t1 | 2 | c1 | V
t1 | 3 | c1 | I
t2 | 3 | c1 | V
t1 | 4 | c1 | V
t1 | 5 | c1 | I
所以我需要复制缺失的行
我正在使用
INSERT INTO table (type,ref,code,state)
SELECT 't2',ref,code,'V' FROM table
WHERE EXISTS (SELECT ref,code,count(*) from table GROUP BY ref,code HAVING count(*)=1)
AND state='I'
但我得到
Violation of PRIMARY KEY
我试过
WHERE NOT EXISTS (SELECT ref,code,count(*) from table GROUP BY ref,code HAVING count(*)>1)
AND state='I'
并没有发生任何事情。知道如何执行此操作吗?
如果是主键,必须是唯一的,不能为空定义。因此,如果您需要两个或更多状态,则需要另一个 table,或另一个字段(如果只有两个),而不是寻求查询
您可以使用以下查询来获取要重复的行:
SELECT type, ref, code, state
FROM mytable AS t1
WHERE state = 'I' AND type = 't1' AND
NOT EXISTS (SELECT 1
FROM mytable AS t2
WHERE t1.ref = t2.ref AND t1.code = t2.code AND
state = 'V' AND type = 't2')
因此,INSERT
语句可以如下所示:
INSERT INTO mytable
SELECT 't2', ref, code, 'V'
FROM mytable AS t1
WHERE state = 'I' AND type = 't1' AND
NOT EXISTS (SELECT 1
FROM mytable AS t2
WHERE t1.ref = t2.ref AND t1.code = t2.code AND
state = 'V' AND type = 't2')
试试这个代码。
INSERT INTO #TAB
SELECT 't2', REF, CODE, 'V' FROM #TAB WHERE stateS='I'
AND REF NOT IN (SELECT REF FROM #TAB WHERE stateS='V' AND typeSS='T2')
我有这个 table 有多列。主键是 (type,ref,code)
,行类型为 t1
,t2
,有两种状态有效 (V)
和无效 (I)
。
状态 t1
中的每个无效行都应该在状态 t2
中有一个有效行,
但是我的 table 已经有一些状态为无效的行,这些行在状态 t2
.
示例:
type | ref | code | state .....
----------------------------------------
t1 | 1 | c1 | V
t1 | 2 | c1 | V
t1 | 3 | c1 | I
t2 | 3 | c1 | V
t1 | 4 | c1 | V
t1 | 5 | c1 | I
所以我需要复制缺失的行
我正在使用
INSERT INTO table (type,ref,code,state)
SELECT 't2',ref,code,'V' FROM table
WHERE EXISTS (SELECT ref,code,count(*) from table GROUP BY ref,code HAVING count(*)=1)
AND state='I'
但我得到
Violation of PRIMARY KEY
我试过
WHERE NOT EXISTS (SELECT ref,code,count(*) from table GROUP BY ref,code HAVING count(*)>1)
AND state='I'
并没有发生任何事情。知道如何执行此操作吗?
如果是主键,必须是唯一的,不能为空定义。因此,如果您需要两个或更多状态,则需要另一个 table,或另一个字段(如果只有两个),而不是寻求查询
您可以使用以下查询来获取要重复的行:
SELECT type, ref, code, state
FROM mytable AS t1
WHERE state = 'I' AND type = 't1' AND
NOT EXISTS (SELECT 1
FROM mytable AS t2
WHERE t1.ref = t2.ref AND t1.code = t2.code AND
state = 'V' AND type = 't2')
因此,INSERT
语句可以如下所示:
INSERT INTO mytable
SELECT 't2', ref, code, 'V'
FROM mytable AS t1
WHERE state = 'I' AND type = 't1' AND
NOT EXISTS (SELECT 1
FROM mytable AS t2
WHERE t1.ref = t2.ref AND t1.code = t2.code AND
state = 'V' AND type = 't2')
试试这个代码。
INSERT INTO #TAB
SELECT 't2', REF, CODE, 'V' FROM #TAB WHERE stateS='I'
AND REF NOT IN (SELECT REF FROM #TAB WHERE stateS='V' AND typeSS='T2')