我希望能够使用mysql在mysql表中获取最后一个插入的id。
示例:
INSERT INTO groups (name, customer_id)
SELECT
groups.name as name,
'2' as customer_id
FROM products
LEFT JOIN groups ON products.group_id=groups.id
WHERE customer_id=1;
既然我已经从一个用户中选择了一个组并为另一个用户创建了一个具有相同名称的新组,我想更新所有产品以获得新的组ID而不是旧组。
UPDATE products SET
group_id=...last inserted id...
WHERE customer_id=2;
这可能只使用mysql吗?
答案 0 :(得分:2)
UPDATE products SET
group_id = LAST_INSERT_ID()
WHERE customer_id=2;
那应该有用..
如果INSERT
出错,您应该使用交易来阻止UPDATE
,反之亦然。这有助于数据的完整性
START TRANSACTION;
INSERT INTO groups (name, customer_id)
SELECT
groups.name as name,
'2' as customer_id
FROM products
LEFT JOIN groups ON products.group_id=groups.id
WHERE customer_id=1;
UPDATE products SET
group_id = LAST_INSERT_ID()
WHERE customer_id=2;
COMMIT;