今天发现数据库中有一些数据乱了我需要做一个临时表来存储数据,我们根据条件来把指定ID的数据保存到临时表,然后进行数据替换操作,但在使用select into from中发现许多的问题,下面我把整理个过程与大家分享一下.
表如下所示,代码如下:
SELECT * FROM `test_table_draw` WHERE `borough_id`>=10266 and `borough_id`<=12354
户型表:SELECT * FROM `test_table_pic` WHERE `borough_id`>=10266 and `borough_id`<=12354
相册表,创建一个备份表,代码如下:
- CREATETABLEIFNOTEXISTS`test_table_tp`(
- `id`int(11)NOTNULLAUTO_INCREMENT,
- `pic_url`varchar(200)NOTNULL,
- `pic_thumb`varchar(200)DEFAULTNULL,
- `pic_desc`varchar(200)DEFAULTNULL,
- `borough_id`int(11)NOTNULL,
- `creater`varchar(20)DEFAULTNULL,
- `addtime`int(11)DEFAULTNULL,
- PRIMARYKEY(`id`),
- KEY`borough_id`(`borough_id`)
- )ENGINE=MyISAMDEFAULTCHARSET=utf8AUTO_INCREMENT=97289;
语法,代码如下:Insert into Table2(field1,field2,...) select value1,value2,... from Table1
例子:Insert into test_table_tp select * from test_table_draw where `borough_id`>=10266 and `borough_id`
错误提示,代码如下:
- INSERTINTOtest_table_tp
- SELECT*
- FROMtest_table_draw
- WHERE`borough_id`>=10266
- AND`borough_id`
MySQL 返回:#1136 - Column count doesn't match value count at row 1
解决,代码如下:
- Insertinto(id,pic_url,pic_thumb,pic_desc,borough_id,creater,addtime)test_table_tpselectid,pic_url,pic_thumb,pic_desc,borough_id,creater,addtimefromtest_table_drawwhere`borough_id`>=10266and`borough_id`<=12354
后来发现上面不对时又找如下代码:
Select * Into new_table_name from old_table_name;
测试仪:Select * Into test_table_tp1 from test_table_draw where `borough_id`>=10266 and `borough_id` <=12354
执行后错误,错误SQL查询,代码如下:
- SELECT*
- INTOtest_table_tp
- FROMtest_table_draw
- WHERE`borough_id`>=10266
- AND`borough_id`
- LIMIT0,30
MySQL 返回:#1327 - Undeclared variable: test_table_tp
网上找到提示要求目标表Table2不存在,因为在插入时会自动创建表Table2,并将Table1中指定字段数据复制到Table2中,代码如下:
Select * Into test_table_tp1 from test_table_draw where `borough_id`>=10266 and `borough_id` <=12354
gg查一下发现原来 mysql 数据库是不支持 SELECT INTO FROM 这种语句的,但是经过研究是可以通过另外一种变通的方法解决这个问题的,代码如下:
Create table Table2 (Select * from Table1);
这种语句代替,代码如下:SELECT vale1, value2, value3 into Table2 from Table1;
下面看一个本人实际操作中的例子吧,代码如下:
- Createtablewww.phpfensi.com (SelectA.id,B.idastypeId,A.brand,A.quanpin,A.simplefrombrandsasA,cartypeasBwhereA.type=B.namegroupbyA.brand);
这个是关联两个表得出一个查询结果,然后将结果插入到一个新创建的表 www.phpfensi.com 中.
好了现在我再来做,代码如下:
Create table pic_test (Select * from test_table_draw where `borough_id`>=10266 and `borough_id` <=12354)
成功了啊,您运行的 SQL 语句已经成功运行了,查询花费 0.5645 秒.
SQL 查询,代码如下:
- CREATETABLEpic_test(
- SELECT*
- FROMtest_table_draw
- WHERE`borough_id`>=10266
- AND`borough_id`<=12354
- )