[英]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"? 我怎样才能从表users中获取用户名和电子邮件,并将其插入到我的表“ reserved_data”中?
The table reserved_data looks like this: 该表reserved_data如下所示:
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. 由于reserved_data
表的表布局,您无法直接执行此操作。 Why do you do that? 你为什么要这么做? Why haven't you got a deleted_users
table, containing their username and email? 为什么没有一个包含他们的用户名和电子邮件的deleted_users
表? 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. 也许您可以通过简单地向用户表中添加(in)active
列来解决所有问题。 One rarely wants to really delete
data. 人们很少想真正delete
数据。
Also you can use on delete trigger to log data to reserved_data table. 您也可以使用删除触发器将数据记录到reserved_data表中。 Just move your reserved_data insert to trigger 只需将您的reserved_data插入移动即可触发
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. 您不需要它,不需要还原已删除的用户,这会带来很多新问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.