MYSQL / php基本问题

时间:2011-02-18 09:27:24

标签: php mysql

我想查看表T1中是否存在指定的值。如果值存在,我想在表T2

中输入值

我如何在PHP中执行此操作?

我想检查存在,然后通过以下命令插入值

我想用这种格式

if ( table1.id = Exist's )

then 

{insert into  table2 ( values ) }

使用PHP编写此代码的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

嗯,这可能会对你有帮助。

更新的答案

好吧,对于表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;  

适用于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那么,你会追加null

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