首先:Jan Dvorak 和 Michael Berkowski 所说的都是绝对正确的。因此,请仔细检查您是否真的需要此 hack,因为您不需要的可能性非常大。
但以防万一,只是为了它,这会将所有 ID 插入到一个表中 - 只要它们是主键,并且它们不存在。
几乎任何其他方式都更好(除了可能手工完成),但需要 MySQL 或其他语言的过程。
-- insert IDs from 1 to 1701, plus another field "otherfield" with value "othervalue"
-- The maximum ID here is about 2400, but you said you needed at most 1400.
-- And you can add 1000 instead of 1 to the value of 'id' and run it again
-- to insert ids from 1000 to 2701 :-)
INSERT IGNORE INTO yourtable
(id, otherfield)
SELECT id, 'othervalue'
FROM (
SELECT 1+a.x+b.x*7+c.x*49+d.x*343 AS id FROM
( SELECT 0 AS x UNION SELECT 1 UNION SELECT 2 UNION
SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 ) AS a
JOIN
( SELECT 0 AS x UNION SELECT 1 UNION SELECT 2 UNION
SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 ) AS b
JOIN
( SELECT 0 AS x UNION SELECT 1 UNION SELECT 2 UNION
SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 ) AS c
JOIN
( SELECT 0 AS x UNION SELECT 1 UNION SELECT 2 UNION
SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 ) AS d
) AS generated
WHERE generated.id < 1701;
正如我所说,这是一种非常丑陋的做事方式。
如果您有任何可用的语言,您可以生成插入查询并运行它们,例如在 bash 中:
( for id in $( seq 1 1400 ); do
echo "INSERT IGNORE INTO mytable ( id, otherfield ) VALUES ( $id, 'hello' );"
done ) | mysql databasename
或者在 PHP、python 或 Perl 中——你只需要生成一个 SQL INSERT 语句的形式
INSERT IGNORE INTO mytable ( id ) VALUES ( ... );
并用递增计数器填充空白,然后将语句发送到数据库。将IGNORE
跳过已经存在的值。如何填空取决于您选择的语言。如果您需要填充其他字段,请id
在空格后面输入名称及其默认值。