我需要用大约一百条假记录填充当前空表,以模拟过去两年的登录来测试我的代码。
登录表架构看起来像:
CREATE TABLE `Logins` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`User_ID` int(11) NOT NULL,
`Date_Login` datetime NOT NULL,
`Location` enum('site','admin') NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
一般来说,我真的是 SQL 新手,所以,我根本不知道查询过去应该是什么
INSERT INTO `Logins` (`User_ID`,`Date_Login`,`Location`) VALUES ...
样子我需要的是在 Logins 中插入 N 个条目(比如说 100 个)
以便
User_ID
从 Users
表的 ID
字段中提取其值
Date_Login
应介于 2 年之间以前和现在的
Location
应该在 'site'
和 'admin'
之间交替,但 'site'
的比重更大加权(比如 80% 的时间)。
希望我能收集一些 SQL-fu 来帮助将来解决类似的问题:D
谢谢!
(我使用的是MySQL 5.1)
I need to populate a currently empty table with a hundred or so fake records to simulate logins over the past two years to test my code with.
The login table schema looks like:
CREATE TABLE `Logins` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`User_ID` int(11) NOT NULL,
`Date_Login` datetime NOT NULL,
`Location` enum('site','admin') NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
I really am new at SQL in general, so, I don't have the slightest idea what the query should look like past
INSERT INTO `Logins` (`User_ID`,`Date_Login`,`Location`) VALUES ...
What I need is insert N entries (lets say 100) into Logins
so that
User_ID
draws its values from the Users
table's ID
field
Date_Login
should be between 2 years ago and now
Location
should alternate between 'site'
and 'admin'
, but with 'site'
more heavily weighted (say 80% of the time).
Hopefully, I can glean some SQL-fu to help with similar problems in the future :D
Thanks!
(I'm using MySQL 5.1)
发布评论
评论(2)
下面是一条 SQL 语句,用于将一行插入到 Logins 表中。您可以重复运行此命令(例如在存储过程中)以获取多条记录。您必须多次运行它才能获取多条记录,因为如果将
LIMIT 1
增加到LIMIT 10
,您将获取 10 条记录,但User_ID
值每条记录都相同。通常,ORDER BY RAND() 是不好的风格,因为它效率低下,但这不是一个对性能敏感的任务。
Here is an SQL statement to insert a single row into the Logins table. You can run this repeatedly (e.g. in a stored procedure) to get multiple records. You have to run it multiple times to get multiple records because if you increase
LIMIT 1
toLIMIT 10
you will get 10 records but theUser_ID
values will be the same for each record.Normally
ORDER BY RAND()
is bad style because it is inefficient, but this isn't a performance-sensitive task.如果您想使用完整的 SQL 解决方案,请按以下步骤创建循环: http://dev.mysql.com/doc/refman/5.1/en/iterate-statement.html
要获得随机日期,您可以将 RAND() 与 +、* 和一些时间戳结合使用。
If you want to use a full SQL solution, here is how you can create a loop: http://dev.mysql.com/doc/refman/5.1/en/iterate-statement.html
To get a random date, you can use RAND() in combination with +, * and some timestamps.