2011-02-18 59 views
0

我想看看錶T1中是否有指定的值。如果值存在,我想輸入表中的值T2MYSQL/php基本問題

我該怎麼做PHP

我要檢查是否存在然後通過以下命令

我想在這種格式

if (table1.id = Exist's) 

then 

{insert into table2 (values) } 

什麼是寫這個代碼用PHP正確的方式插入值是多少?

+1

你想記錄做的,如果它已經存在,做什麼?你想更新它還是忽略它或其他? – 2011-02-18 09:33:29

+0

你在檢查哪個值?你的代碼中的``link`表,T1`或`T2`在你的問題中? `T1`對你正在檢查的列有唯一的約束嗎? – 2011-02-18 09:38:49

回答

3

嗯,這可能會幫助你。

修訂ANSWER

那麼,對於表TB1

+-------+-------------+------+-----+---------+-------+ 
| Field | Type  | Null | Key | Default | Extra | 
+-------+-------------+------+-----+---------+-------+ 
| fld1 | varchar(20) | YES |  | NULL |  | 
| fld2 | varchar(20) | YES |  | NULL |  | 
| fld3 | varchar(20) | YES |  | NULL |  | 
+-------+-------------+------+-----+---------+-------+ 

和表TB2

+-------+-------------+------+-----+---------+-------+ 
| Field | Type  | Null | Key | Default | Extra | 
+-------+-------------+------+-----+---------+-------+ 
| fld1 | varchar(20) | YES |  | NULL |  | 
| fld2 | varchar(20) | YES |  | NULL |  | 
| fld3 | varchar(20) | YES |  | NULL |  | 
+-------+-------------+------+-----+---------+-------+ 

INSERT INTO tb1 (fld1, fld2, fld3) SELECT tb2.fld1, tb2.fld2, 
    tb2.fld3 FROM tb2; 

Works的version 5.1.49的答案會是

$sql = "INSERT INTO table1 (fld1, fld2, fld3) SELECT table2.fld1, ". 
    table2.fld2, table2.fld3 FROM table2 WHERE table2.id= ".$somevalue; 

UPDATE不需要檢查ID,它會自動檢查,如果沒有ID的話,你也會追加空

INSERT INTO table2 (fld1, fld2, fld3) SELECT table1.fld1, table1.fld2, table1.fld3 
FROM table1 where table1.id = someid ;