没有唯一键的mysql插入如果不存在

时间:2014-04-03 20:15:39

标签: php mysql sql

正如在MySQL: Insert record if not exists in tablehttps://stackoverflow.com/a/5289299/2037323中所讨论的那样,我正在尝试运行以下来自php的查询,$result = mysql_query($query, $con);会返回true,但新记录不会添加到teamshalf }表。这里有什么不对? http://pastebin.com/xCqWpKcb是我用于两个表的数据。 这里要提到的一点是我不能在这里使用唯一键。所以请告诉我们是否有非独特的解决方案。

INSERT teamshalf
(`yearID` , `lgID` , `teamID` , `Half` , 
`divID` , `DivWin` , `Rank` , `G` , `W` , `L`)
 SELECT DISTINCT t1.`yearID` , t1.`lgID` , t1.`teamID` ,
 t1.`Half` , t1.`divID` , t1.`DivWin` , t1.`Rank` , t1.`G` , t1.`W` , t1.`L` 
 FROM `teamshalf_TEMP` t1 LEFT JOIN `teamshalf` t2 ON t1.`yearID` = t2.`yearID`
 AND t1.`lgID` = t2.`lgID` AND t1.`teamID` = t2.`teamID`
 AND t1.`Half` = t2.`Half` AND t1.`divID` = t2.`divID`
 AND t1.`DivWin` = t2.`DivWin` AND t1.`Rank` = t2.`Rank`
 AND t1.`G` = t2.`G` AND t1.`W` = t2.`W` AND t1.`L` = t2.`L`
 WHERE t1.`yearID` IS NULL AND t1.`lgID` IS NULL AND t1.`teamID` IS NULL
 AND t1.`Half` IS NULL AND t1.`divID` IS NULL AND t1.`DivWin` IS NULL
 AND t1.`Rank` IS NULL AND t1.`G` IS NULL AND t1.`W` IS NULL AND t1.`L` IS NULL

正如@Arjan所提到的,我使用的是t1.col_name is null而不是t2.col_name is null。所以通过修改我得到了理想的结果。

2 个答案:

答案 0 :(得分:2)

查询成功(否则mysql_query()不会返回true)但它不会插入任何行。对此的唯一解释是SELECT部分导致空集。这是因为LEFT JOIN会返回t1中但t2中不存在的行,但选择是在NULL中的t1行中完成的。

这应该有效:

INSERT teamshalf
(`yearID` , `lgID` , `teamID` , `Half` , 
`divID` , `DivWin` , `Rank` , `G` , `W` , `L`)
 SELECT DISTINCT t1.`yearID` , t1.`lgID` , t1.`teamID` ,
 t1.`Half` , t1.`divID` , t1.`DivWin` , t1.`Rank` , t1.`G` , t1.`W` , t1.`L` 
 FROM `teamshalf_TEMP` t1 LEFT JOIN `teamshalf` t2 ON t1.`yearID` = t2.`yearID`
 AND t1.`lgID` = t2.`lgID` AND t1.`teamID` = t2.`teamID`
 AND t1.`Half` = t2.`Half` AND t1.`divID` = t2.`divID`
 AND t1.`DivWin` = t2.`DivWin` AND t1.`Rank` = t2.`Rank`
 AND t1.`G` = t2.`G` AND t1.`W` = t2.`W` AND t1.`L` = t2.`L`
 WHERE t2.`yearID` IS NULL

另请注意,mysql_query()已弃用。并且您应该声明必须包含NOT NULL数据的列,因此不会接受NULL。而且你的查询会很慢,因为你没有使用索引。

答案 1 :(得分:1)

恕我直言,您应该通过连接使记录唯一的字段来创建唯一键。 (记录永远不会与另一条记录完全相同)。 例如:

insert into table_a
(field1, field2, field3, field4)
select t_field1, t_field2, t_field3, t_field4
from temp_table 
where concatenate(t_field1, t_field2, t_field3, t_field4)
not in (select concatenate(field1, field2, field3, field4) from table_a)

我不确定在mysql中连接的等价是什么,但我希望你理解这个解释。