[英]how to insert into a table records from a table that have records in another table?
I have table parent
and table kids
, a parent can have some kids in the kids table (0 or more). 我有桌子parent
和桌子kids
,父母可以在孩子表中有一些孩子(0个或更多)。
I want to insert to new table parentWithKids
only the parents that have kids in the kids table. 我想将仅在kids表中有孩子的parents插入到新表parentWithKids
中。
So I tried something like: 所以我尝试了类似的东西:
INSERT INTO parentWithKids
SELECT *
FROM parent p
INNER JOIN kids k ON p.id = k.parent_id
but its not running...what is the issue here? 但是它没有运行...这里是什么问题?
I assume following schema. 我假设遵循以下架构。
parent: 父:
CREATE TABLE IF NOT EXISTS `parent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
kids 孩子
CREATE TABLE IF NOT EXISTS `kids` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
parentwithkids parentwithkids
CREATE TABLE IF NOT EXISTS `parentwithkids` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL,
`kids` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
Here is the final query to retrieve the list of parents with number of kids. 这是检索带有孩子数量的父母列表的最终查询。
INSERT INTO parentWithKids(parent_id, kids)
SELECT DISTINCT p.id, count(k.id)
FROM parent p
INNER JOIN kids k ON p.id = k.parent_id
GROUP BY k.parent_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.