2017-02-23 23 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