Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A quick SQL query to generate example data

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)

like image 883
Austin Hyde Avatar asked Apr 29 '26 07:04

Austin Hyde


1 Answers

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 to LIMIT 10 you will get 10 records but the User_ID values will be the same for each record.

INSERT INTO `Logins` (`User_ID`, `Date_Login`, `Location`)
SELECT
  users.ID AS `User_ID`,
  DATE_SUB(NOW(), INTERVAL FLOOR(1 + (RAND() * (365 * 2))) DAY) AS `Date_Login`,
  IF(RAND() > 0.8, 'admin', 'site') AS `Location`
FROM users
ORDER BY RAND()
LIMIT 1;

Normally ORDER BY RAND() is bad style because it is inefficient, but this isn't a performance-sensitive task.

like image 126
dvogel Avatar answered May 01 '26 23:05

dvogel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!