我想删除数据库中所有在另一个表中没有引用的行:
还行吧:
mysql> DELETE FROM auth_user WHERE username = 'Sample41';
Query OK, 1 row affected (0.02 sec)
这是不行的:
mysql> DELETE FROM auth_user WHERE username = 'Sample98';
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`mydatabase`.`school_subjects`, CONSTRAINT `user_id_refs_id_9e8f6fd7` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))
所以我的目标是获得一个查询,该查询将删除在其他表中没有引用的所有用户(他们将以'Sample'开头)(实际上只有一个表'school_subjects')
谢谢你。,
更新:
mysql> describe school_subjects;
+------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(500) | NO | | NULL | |
| user_id | int(11) | NO | MUL | NULL | |
| created_by | varchar(64) | NO | | NULL | |
| created_time | datetime | NO | | NULL | |
| num_of_followers | int(11) | NO | | NULL | |
+------------------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
mysql> describe auth_user;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(30) | NO | UNI | NULL | |
| first_name | varchar(30) | NO | | NULL | |
| last_name | varchar(30) | NO | | NULL | |
| email | varchar(75) | NO | | NULL | |
| password | varchar(128) | NO | | NULL | |
| is_staff | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| is_superuser | tinyint(1) | NO | | NULL | |
| last_login | datetime | NO | | NULL | |
| date_joined | datetime | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
11 rows in set (0.00 sec)