gpt4 book ai didi

mysql - 根据另一个查询的结果为新 ID 插入重复行

转载 作者:行者123 更新时间:2023-11-29 00:31:06 26 4
gpt4 key购买 nike

因此,我会尽力描述我尝试构建的查询。

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

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

这会将用户 ID 1 的现有行复制到用户 ID 10。

但我想为所有处于事件状态且不存在于此表中的用户 ID 运行此操作。所以我想首先执行这个查询:

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

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

提前致谢!

最佳答案

一种方法是创建一个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 Fiddle Demo

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

关于mysql - 根据另一个查询的结果为新 ID 插入重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16462930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com