我有这段代码,但有时它会插入双记录。我无法为字段user_subid设置唯一键。

$sql="SELECT `user_subid` FROM `clicks` WHERE `user_subid`='".$user_subid."'";
$query=mysql_query($sql);
if(mysql_num_rows($query)==0){
    $sqlIns="INSERT INTO `clicks` (`file_id`, `country`, `date`, `timeClick`, `user_subid`) VALUES ('".$fileid."', '".$country."', '".$date."', '".$timeClick."', '".$user_subid."')";
    if(mysql_query($sqlIns)==true){
        echo 1;
    }
    else { echo 0;}
}


我尝试过:


INSERT INTO `clicks` (
`id` ,
`file_id` ,
`country` ,
`date` ,
`timeClick` ,
`user_subid`
)
VALUES (
NULL , '1500', 'Canada', '2014-05-24', '1400934475', '7c282b9227328778680d5826e01f6d'
) WHERE NOT EXISTS (SELECT * FROM `clicks` WHERE `user_subid`='7c282b9227328778680d5826e01f6d');


但这不起作用。

最佳答案

你在找这个吗?


  INSERT IGNORE INTO点击(id,file_id,国家,日期,timeClick,user_subid)
      值(NULL,'1500','Canada','2014-05-24','1400934475','7c282b9227328778680d5826e01f6d')


编辑:

 INSERT INTO `clicks` (
  `id` ,
  `file_id` ,
  `country` ,
  `date` ,
  `timeClick` ,
  `user_subid`
 )
 SELECT `id` ,
`file_id` ,
`country` ,
`date` ,
`timeClick` ,
`user_subid`
FROM
 (SELECT NULL id , '1500' `file_id` , 'Canada' `country` , '2014-05-24' `date` , '1400934475' `timeClick` , '7c282b9227328778680d5826e01f6d' `user_subid`) a
LEFT JOIN `clicks` b ON
  a.id = b.id AND a.`file_id` = b.`file_id` AND a.`user_subid` = b.`user_subid`
WHERE b.`user_subid` IS NULL;


或不存在

  INSERT INTO `clicks` (
  `id` ,
  `file_id` ,
  `country` ,
  `date` ,
  `timeClick` ,
  `user_subid`
 )
 SELECT `id` ,
`file_id` ,
`country` ,
`date` ,
`timeClick` ,
`user_subid`
FROM
 (SELECT NULL id , '1500' `file_id` , 'Canada' `country` , '2014-05-24' `date` , '1400934475' `timeClick` , '7c282b9227328778680d5826e01f6d' `user_subid`) a
 WHERE NOT EXISTS (
   SELECT 1
   FROM `clicks`
   WHERE `user_subid` = '7c282b9227328778680d5826e01f6d')

关于php - 如果不存在唯一键,则插入记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23846106/

10-11 05:03