作为一名php程序员
对sql的使用仅局限一些简单的增删改查操作,和一些关联查询
可别忘了sql本身就是一门编程语言,有时候一条sql就可以搞定了,没必要使用脚本来实现
今天说的是sql的关联更新操作
```
mysql> create table test1(id int primary key auto_increment,name varchar(50),age int);
Query OK, 0 rows affected (0.02 sec)
mysql>
mysql>
mysql> create table test2(id int primary key auto_increment,name varchar(50),age int);
Query OK, 0 rows affected (0.03 sec)
mysql> insert into test1(id) values(1);
Query OK, 1 row affected (0.01 sec)
mysql> insert into test1(id) values(2);
Query OK, 1 row affected (0.00 sec)
mysql> select *from test1;
+----+------+------+
| id | name | age |
+----+------+------+
| 1 | NULL | NULL |
| 2 | NULL | NULL |
+----+------+------+
2 rows in set (0.00 sec)
mysql> insert into test2(id,name,age) values(1,'xiaoming',10);
Query OK, 1 row affected (0.01 sec)
mysql> insert into test2(id,name,age) values(2,'xiaohong',8);
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> select *from test1 left join test2 on test1.id=test2.id;
+----+------+------+------+----------+------+
| id | name | age | id | name | age |
+----+------+------+------+----------+------+
| 1 | NULL | NULL | 1 | xiaoming | 10 |
| 2 | NULL | NULL | 2 | xiaohong | 8 |
+----+------+------+------+----------+------+
2 rows in set (0.00 sec)
mysql> update test1,test2 set test1.name=test2.name,test1.age=test2.age where test1.id=test2.id;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql>
mysql>
mysql> select *from test1 left join test2 on test1.id=test2.id;
+----+----------+------+------+----------+------+
| id | name | age | id | name | age |
+----+----------+------+------+----------+------+
| 1 | xiaoming | 10 | 1 | xiaoming | 10 |
| 2 | xiaohong | 8 | 2 | xiaohong | 8 |
+----+----------+------+------+----------+------+
2 rows in set (0.00 sec)
```
是不是非常方便与简单