1

所以我会尽力描述我正在尝试构建的查询。

我有一个表,我将调用user_records,其中包含一些用于关系 ID 的数据(几行),例如 userId (来自表users)。对于每一行,我需要为另一个用户复制每一行。我知道我可以运行这个:

INSERT INTO user_records (userId, column1, column2, ...)  
SELECT 10 as userId, column1, column2...  
FROM user_records 
WHERE userId = 1  

这会将 userId 1 的现有行复制到 userId 10。

但我想为所有处于活动状态且此表中尚不存在的 userId 运行此命令。所以我想基本上先执行这个查询:

SELECT userID  
FROM users  
WHERE users.active = 1  
AND NOT EXISTS (  
SELECT * FROM user_records 
WHERE users.userId = user_records.userId)

使用 JOINS 或简单地组合 2 个查询,我可以运行此查询并替换前一个查询中的 10 个,以便它复制一系列 userId 的行吗?

提前致谢!

4

1 回答 1

1

一种方法是创建一个CROSS JOIN

insert into user_records (userId, column1)
select u.userId, ur.column1
from user_records ur
  cross join users u 
where ur.userId = 1
  and u.active = 1
  and u.userId not in (select userId from user_records);

SQL 小提琴演示

这将为表中不存在的每个 userId 将新行插入 user_records,从 UserId 1 复制数据。

于 2013-05-09T13:38:07.963 回答