0

基本上,我想插入表中,从同一个表中获取值 id,像这样

$sql = ("INSERT INTO commande (idfichecmd,idproduit,idclt,qte,datecmd)
(SELECT MAX(idfichecmd)+1 ,'1' AS idproduit ,'$idC' AS idclt ,'$fb' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'2' AS idproduit ,'$idC' AS idclt ,'$g' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'3' AS idproduit ,'$idC' AS idclt ,'$pi' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'4' AS idproduit ,'$idC' AS idclt ,'$ft' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'5' AS idproduit ,'$idC' AS idclt ,'$sd' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'6' AS idproduit ,'$idC' AS idclt ,'$ad' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'7' AS idproduit ,'$idC' AS idclt ,'$vs' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'8' AS idproduit ,'$idC' AS idclt ,'$wi' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'9' AS idproduit ,'$idC' AS idclt ,'$equip' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'10' AS idproduit ,'$idC' AS idclt ,'$fo' AS qte,'$date' FROM commande),
(SELECT MAX(idfichecmd) ,'11' AS idproduit ,'$idC' AS idclt ,'$fh' AS qte,'$date' FROM commande)")or die(mysql_error());
$result = mysql_query($sql) or die("Unable to add commande : ". mysql_error());   
mysql_close();

但是,这个不起作用,有人知道为什么吗?

4

1 回答 1

0

可以使用UNION

INSERT INTO commande (idfichecmd, idproduit, idclt, qte, datecmd)
  SELECT MAX(idfichecmd)+1,  1, '$idC', '$fb'   , '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  ,  2, '$idC', '$g'    , '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  ,  3, '$idC', '$pi'   , '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  ,  4, '$idC', '$ft'   , '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  ,  5, '$idC', '$sd'   , '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  ,  6, '$idC', '$ad'   , '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  ,  7, '$idC', '$vs'   , '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  ,  8, '$idC', '$wi'   , '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  ,  9, '$idC', '$equip', '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  , 10, '$idC', '$fo'   , '$date' FROM commande
UNION ALL
  SELECT MAX(idfichecmd)  , 11, '$idC', '$fh'   , '$date' FROM commande

但是首先MAX(idfichecmd)在 PHP 中获取,然后使用INSERT ... VALUES(记住在事务中执行操作以保持原子性)可能更容易:

INSERT INTO commande (idfichecmd, idproduit, idclut, qte, datecmd) VALUES
  ($id+1, 1, '$idC', '$fb', '$date'),
  ($id  , 2, '$idC', '$g' , '$date'),
  -- etc.

或者,如果您只是想为每条新记录添加一个 incremented idfichecmd,请考虑制作该列AUTO_INCREMENT(MySQL 会自动为您完成所有这些操作):

ALTER TABLE commande MODIFY idfichecmd INT AUTO_INCREMENT;
INSERT INTO commande (idproduit, idclut, qte, datecmd) VALUES
  (1, '$idC', '$fb', '$date'),
  (2, '$idC', '$g' , '$date'),
  -- etc.
于 2012-05-31T10:55:35.790 回答