我有 1 个表 auction_activity_notifications
,需要从 users
表和列 item_watch
插入 id,还需要加入 email_templates
表,还需要插入 auction_activity_notifications
我在哪里插入用户 ID 和 item_watch 列,我需要加入 email_templates
并将 ID 从 email_templates
插入到 auction_activity_notifications
INSERT INTO auction_activity_notifications (id_user, id_target)
SELECT id, item_watch
FROM users AS u
LEFT JOIN auction_activity_notifications AS aa
ON u.id = aa.id_user
AND
u.item_watch=aa.id_target
我在 auction_activity_notifications
中有这些列
最后我需要将当前日期插入到created_date_time
id_email_templates、id_user、id_target、create_date_time
最佳答案
在查询中再添加一个联接
INSERT INTO auction_activity_notifications (id_email_templates,id_user, id_target,created_date_time)
SELECT et.id,u.id, u.item_watch ,NOW()
FROM users AS u
LEFT JOIN auction_activity_notifications AS aa
ON u.id = aa.id_user
LEFT JOIN email_templates et ON (aa.id_email_templates=et.id)
AND
u.item_watch=aa.id_target
请注意,当连接表中的列相同时,请使用带有列名称的表别名,这样可以保护列的不明确条件
对于当前日期时间,您可以使用数据类型
作为时间戳
,并通过设置CURRENT_TIMESTAMP
来设置表列默认值,并删除 NOW()
来自 select 和 created_date_time
来自插入,它会自动添加当前时间戳并记录插入
ALTER TABLE `table` CHANGE `created_date_time` `created_date_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
关于php - 插入有2个连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18328047/