简体   繁体   中英

Select from table, and insert data to another - Multiply data -SQL

I have a button that will delete all users that fits into this query:

DELETE FROM users WHERE lastlogin < ".time()." - ".$sdata['activitylimit']."*3600

Although, I have to take some parts of each users data, and put it into another table ("username" and "email")

How can I take the users username AND email from the table users , and insert it into my table "reserved_data"?

The table reserved_data looks like this:

id (just the id)
data (the email or username value)
type (what type of data is it((username/email)))

You can't do that directly, thanks to the table layout of the reserved_data table. Why do you do that? Why haven't you got a deleted_users table, containing their username and email? That way you could do this:

$q1 = "INSERT INTO deleted_users (username, email) SELECT username, email FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)";

$q2 = "DELETE FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)";

If you won't change the table, use something like this:

$toDelete = mysql_query("SELECT username, email FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)");

while($user = mysql_fetch_assoc($toDelete))
{
    mysql_query("INSERT INTO reserved_data (`data`, `type`) VALUES ('" . $user['username'] . ", 'username'");
    mysql_query("INSERT INTO reserved_data (`data`, `type`) VALUES ('" . $user['email'] . ", 'email'");
}

// Now perform the delete
mysql_query("DELETE FROM users WHERE lastlogin < (".time()." - ".$sdata['activitylimit']." * 3600)");

You see the latter requires more code and is generally a bad idea. You lose the relation between a username and its email address.

Besides, you might want to use transactions, since it's possible for one to not be included in the first query but be included in the second query. You then lose this user's data.

And perhaps you can fix all your problems by simply adding an (in)active column to your users table. One rarely wants to really delete data.

Also you can use on delete trigger to log data to reserved_data table. Just move your reserved_data insert to trigger

I would not recommend approach with deletion mark. You don't need it there is no requirement to restore deleted users and it brings quite much new problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM