我有这个代码,但有时它会插入我的双记录。我无法为字段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');
但它不起作用。
答案 0 :(得分:1)
INSERT IGNORE INTO点击次数(id,file_id,country,date,timeClick,user_subid) VALUES(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;
或使用NOT EXIST
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')
答案 1 :(得分:1)
您的SQL是否有效?
如果要存在记录,则需要更新重新编码。否则插入新的重新编码。试试UPSERT CODE吧。 INSERT ... ON DUPLICATE KEY UPDATE
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
答案 2 :(得分:0)
你有没有尝试改变
$sql="SELECT `user_subid` FROM `clicks` WHERE `user_subid`='".$user_subid."'";
$query=mysql_query($sql);
if(mysql_num_rows($query) < 1){ // change == 0 to < 1
$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;}
}