将“偶数”行插入mysql中的现有表中

时间:2009-07-10 14:25:43

标签: mysql

我有一张桌子:

+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| fooID          | int(11)      | NO   | PRI | NULL    | auto_increment | 
| fooDetails     | varchar(200) | YES  |     | NULL    |                | 
| fooListingID   | int(10)      | YES  |     | NULL    |                | 
| fooStatus      | tinyint(4)   | YES  |     | 0       |                | 
+----------------+--------------+------+-----+---------+----------------+

我想将类似表中的数据与此表合并,但我希望数据是交替的,以便此表中的现有数据都是奇数“fooID”,新插入将是偶数“fooID” ”

想法?

2 个答案:

答案 0 :(得分:3)

我已经解释了你的问题,因为你把所有现有的fooD变成奇数,然后将一些新的,前夕fooDs合并到那个表中。

您可以相当轻松地完成此任务:

#first make all the existing ids odd
UPDATE oldtable SET fooID=fooID*2-1;

#now insert rows from the other table, making sure the ids are even    
INSERT INTO oldtable (fooID,fooDetails,fooListingID,fooStatus)
    SELECT fooID*2,fooDetails,fooListingID,fooStatus FROM newtable;

答案 1 :(得分:1)

您可以插入select语句的结果。使用modulo表示交替ID:

INSERT INTO NewTable
SELECT column1, column2
FROM OldTable
WHERE NOT id % 2