以下更新!
谁可以帮助我
我有一张桌子:
CREATE TABLE `group_c` (
`parent_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`child_id` int(11) DEFAULT NULL,
`number` int(11) DEFAULT NULL,
PRIMARY KEY (`parent_id`)
) ENGINE=InnoDB;
INSERT INTO group_c(parent_id,child_id)
VALUES (1,1),(2,2),(3,3),(4,1),(5,4),(6,4),(7,6),(8,1),(9,2),(10,1),(11,1),(12,1),(13,0);
我想为每个有多个父母的孩子更新数字字段:
SELECT group_concat(parent_id), count(*) as c FROM group_c group by child_id having c>1
结果:
GROUP_CONCAT(PARENT_ID) C
12,11,10,8,1,4 6
9,2 2
6,5 2
所以带有parent_id 12,11,10,8,1,4,9,2,6,5的所有行都应更新为number = 1
我尝试过类似的事情:
UPDATE group_c SET number=1 WHERE FIND_IN_SET(parent_id, SELECT pid FROM (select group_concat(parent_id), count(*) as c FROM group_c group by child_id having c>1));
但这不起作用。
我该怎么做?
SQLFIDDLE:http://sqlfiddle.com/#!2/acb75/5
[编辑]
我试图让这个例子变得简单但真实的东西有点复杂,因为我正在按多个字段进行分组。这是一个新的小提琴:http://sqlfiddle.com/#!2/7aed0/11
答案 0 :(得分:1)
为什么要使用GROUP_CONCAT()
,然后尝试通过FIND_IN_SET()
对其结果做些什么?这不是SQL的工作方式。您可以使用简单的JOIN
来检索记录:
SELECT
parent_id
FROM
group_c
INNER JOIN
(SELECT
child_id,
count(*) as c
FROM
group_c
group by
child_id
having c>1) AS childs
ON childs.child_id=group_c.child_id
- 检查你的modified demo。如果您需要UPDATE
,请使用:
UPDATE
group_c
INNER JOIN
(SELECT
child_id,
count(*) as c
FROM
group_c
group by
child_id
having c>1) AS childs
ON childs.child_id=group_c.child_id
SET
group_c.number=1
答案 1 :(得分:0)
对任何有兴趣的人。这就是我解决它的方式。这是两个问题,但就我而言,这不是一个问题。
UPDATE group_c INNER JOIN (
SELECT parent_id, count( * ) AS c
FROM `group_c`
GROUP BY child1,child2
HAVING c >1
) AS cc ON cc.parent_id = group_c.parent_id
SET group_c.number =1 WHERE number =0;
UPDATE group_c INNER JOIN group_c as gc ON
(gc.child1=group_c.child1 AND gc.child2=group_c.child2 AND gc.number=1)
SET group_c.number=1;
答案 2 :(得分:0)
这是一个类似的解决方案......
UPDATE group_c a
JOIN
( SELECT DISTINCT x.child_id candidate
FROM group_c x
JOIN group_c y
ON y.child_id = x.child_id
AND y.parent_id < x.parent_id
) b
ON b.candidate = a.child_id
SET number = 1;