您好,我在控制台(或在phpmyadmin sql cmd中)调用mysql query select
SELECT HF, ID FROM AH WHERE HF !=0 GROUP BY HF;
之后,我需要为上一次选择的每个返回的行执行命令
foreach
IF (SELECT COUNT(*) FROM `TOT` WHERE `ID` = @selectedID AND `Uto` = @selectedHF ) = 0 THEN
INSERT INTO `TOT` (`ID`, `HF`) VALUES (@selectedID, @selectedHF);
END IF;
endforeach;
如何在mysql中执行此“ foreach”循环?
最佳答案
您可以使用单个查询insert . . . select
来执行此操作。不需要循环,但您确实要检查不存在:
INSERT INTO `TOT` (`ID`, `HF`)
SELECT ID, HF
FROM AH a
WHERE HF <> 0 AND
NOT EXISTS (SELECT 1 FROM TOT WHERE TOT.ID = a.ID AND TOT.UTO = @selectedHF)
GROUP BY HF;
关于mysql - 如何在mySQL查询中为每个结果插入一条记录?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29393366/