如何创建正确的MySQL查询INSERT

时间:2017-02-23 01:18:38

标签: mysql insert

我在MySQL表中有一些数据如下:

2017-02-01: 'A': 'K1': 100
2017-02-01: 'A': 'K2': 200
2017-02-01: 'B': 'K1': 300
2017-02-02: 'A': 'K1': 110
2017-02-02: 'A': 'K2': 210
2017-02-02: 'B': 'K1': 310

我只需要在last(按日期)值不等于new时插入新数据。 例如:insert new 400 if last [A:K1]<>400

我现在使用2个查询来完成这项工作,但插入它的速度很慢:

$res=mysql_query("select * from `table` where `col1`='A' and `col2`='K1' order by 'date' desc limit 1");
$tkol=0;
if($res){while($r=mysql_fetch_assoc($res)){$tkol=$r[0]['col3']; break;}}
if($tkol!=$newVal){
$q="INSERT INTO `table` (`date`,`col1`,`col2`,`col3`) VALUES ('2017-02-10','A','K1',$newVal)";
mysql_query($q);
}

如何在"INSERT ... IF ..."之类的1个mysql查询中编写我的任务? 请帮帮我

2 个答案:

答案 0 :(得分:0)

将重要列用作unique key并使用REPLACE代替INSERT

OR

您可以使用insert ... from select ... where oldval <> newval;

select将没有“from”,并且值将从webserver直接写入其中。

$q="INSERT INTO `table` (`date`,`col1`,`col2`,`col3`) select ".$date.", ".$a.", ".$b.", ".$c." WHERE not exists (select 1 from `table` where col1 = $a ... and date = select(max) date from table)"; 

并且,请记住输入验证!

答案 1 :(得分:0)

尝试使用INSERT INTO SELECT语法:

INSERT INTO `table` (`date`,`col1`,`col2`,`col3`)
SELECT DISTINCT '2017-02-10', 'A', 'K1', $newVal
FROM `table` t1
JOIN (
    SELECT MAX(`date`) AS maxdate, `col1`, `col2`
    FROM `table` 
    WHERE `col1` = 'A'
    AND `col2` = 'K1'
) t2 ON t1.`col1` = t2.`col1` AND t1.`col2` = t2.`col2` AND t1.`date` = t2.`maxdate`
WHERE t1.`col1` = 'A'
AND t1.`col2` = 'K1'
AND t1.`col3` <> $newVal