2017-02-23 34 views
0

我有在MySQL表中的一些数据是这样的:如何建立正确的MySQL查询INSERT

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 

我需要插入只有最后一个(按日期)值不等于新新数据。 例如: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); 
} 

如何写我的任务1的MySQL查询像"INSERT ... IF ..."请帮帮我

回答

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 
+0

谢谢,我今天试试 – mogican

+0

谢谢我的朋友!它工作正确!我很开心!感谢您的帮助! – mogican

+0

脚本与您的查询有更多的执行时间。你可以优化更多吗? – mogican

0

使用重要列作为​​并使用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)"; 

而且,记得输入验证!

+0

我不能设置此列作为唯一的。我有'id'独特的专栏。其他列不能是唯一的。 – mogican

+0

然后使用https://dev.mysql.com/doc/refman/5.7/en/insert-select.html – klepzers

+0

另外,请记住,唯一键可以保存多个列! – klepzers