我从Bill那里得到了答案。但是如何插入在循环选择中找不到的其他默认值?
我正在做这个工作:
SET @createdAt = STR_TO_DATE(NOW(), '%Y-%m-%d %H:%i:%s');
INSERT IGNORE INTO fancy_table (userId, content, createdAt)
-- Values
SELECT
userId,
content,
-- I faked this
REPLACE(some_random_col, 'sometimes-value-does-not-match', @createdAt) as createdAt
FROM users
WHERE foo = 'bar';
如果我想更新更多的 fancy_table
列怎么办? “假”REPLACE
列对我来说是错误的。
编辑:
我怎样才能实现这样的目标:
SET @createdAt = STR_TO_DATE(NOW(), '%Y-%m-%d %H:%i:%s');
INSERT IGNORE INTO fancy_table (userId, content, createdAt, etc...)
VALUES (
(SELECT
userId,
content
FROM users
WHERE foo = 'bar';),
@createdAt,
etc...
)
答案 0 :(得分:1)
您可以直接在 @createdAt
语句中使用 SELECT
:
SET @createdAt = STR_TO_DATE(NOW(), '%Y-%m-%d %H:%i:%s');
INSERT IGNORE INTO fancy_table (userId, content, createdAt)
SELECT
userId,
content,
@createdAt
FROM users
WHERE foo = 'bar';
但是,@createdAt
实际上是您可以使用 CURRENT_TIMESTAMP
或 NOW()
获得的当前时间戳:
INSERT IGNORE INTO fancy_table (userId, content, createdAt)
SELECT
userId,
content,
CURRENT_TIMESTAMP
FROM users
WHERE foo = 'bar';