如何在mySQL查询中插入每个结果的记录?

时间:2015-04-01 14:23:45

标签: mysql

您好我在控制台(或在phpmyadmin sql cmd中)调用mysql查询选择

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”循环?

1 个答案:

答案 0 :(得分:0)

您可以使用单个查询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;