mysql - 如何使用 SQL 查询删除父表和子表行?

标签 mysql

我想从父表和子表中删除行。

例如

我有两个表: 1) 2) 群组成员

group 表有以下字段:

group_id, Group_name, user_id

group_member有以下字段:

id, group_id, user_id

我想删除这样的东西,

假设表有 user_id 2 和 user_id 的所有成员在 group_member 表中可用

表1图片

enter image description here

表2图片

enter image description here

如果触发删除查询 - 所有 id = 19 的记录都将从两者中删除 表格

最佳答案

您需要使用 DELETE CASCADE,只需使用下表并进行测试即可。

-- ----------------------------
-- Table structure for candidate_master
-- ----------------------------
DROP TABLE IF EXISTS `candidate_master`;
CREATE TABLE `candidate_master` (
  `candidate_id` int(10) unsigned NOT NULL,
  `first_name` varchar(100) DEFAULT NULL,
  `middle_name` varchar(100) DEFAULT NULL,
  `last_name` varchar(100) DEFAULT NULL,
  `phone_number` varchar(25) NOT NULL,
  `callerid` varchar(25) DEFAULT NULL,
  `duration` int(11) DEFAULT NULL,
  `city` varchar(50) DEFAULT NULL,
  `state` varchar(80) DEFAULT NULL,
  `date_modified` datetime DEFAULT NULL,
  `key_skills` text,
  `visa` varchar(20) DEFAULT NULL,
  `status` varchar(100) DEFAULT NULL,
  `pvm` enum('voicemail','ping') DEFAULT NULL,
  `id` int(11) NOT NULL,
  `isDNC` enum('NO','YES') NOT NULL DEFAULT 'NO',
  UNIQUE KEY `number` (`phone_number`) USING BTREE,
  KEY `candidate_master_ibfk_1` (`id`),
  CONSTRAINT `candidate_master_ibfk_1` FOREIGN KEY (`id`) REFERENCES `cgListUpdateLog` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Table structure for cgListUpdateLog
-- ----------------------------
DROP TABLE IF EXISTS `cgListUpdateLog`;
CREATE TABLE `cgListUpdateLog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `file_name` varchar(255) DEFAULT NULL,
  `pass` int(11) DEFAULT NULL,
  `fail` int(11) DEFAULT NULL,
  `UpdatedOn` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `status` enum('NEW','PROCESSING','PROCESSED','FAILED') DEFAULT NULL,
  `dialStatus` enum('YES','NO') DEFAULT 'NO',
  `notDialed` int(11) DEFAULT NULL,
  `filestatus` enum('processed','pending') DEFAULT 'processed',
  `comment` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=latin1;

如有任何进一步的帮助,请告诉我!!

关于mysql - 如何使用 SQL 查询删除父表和子表行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35079153/

相关文章:

php - Angular 和 MySQL - 前端过滤与多个查询

php - 使用如下条件从数据库中选择值

PHP - 执行附加查询

c# - DataTable.Columns.Clear 和列排序后的 DataAdapter.Fill NullReferenceException

mysql - 如何在cakephp中获取相关表的COUNT值

php - 查询 : MySQL Table Join

php - 在列值表结构中搜索

mysql - 数据库设计 : how to deal with a table that has non-unique foreign keys

PHP - 来自动态 POST 的动态 SQL 查询

mysql - 如何删除和重新填充 mysql 数据库?