0

下面更新!

谁能帮帮我

我有一张桌子:

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);

我想将每个有多个父母的孩子的数字字段更新为 1:

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

4

3 回答 3

1

为什么使用GROUP_CONCAT()然后尝试通过它的结果做一些事情FIND_IN_SET()?这不是 SQL 的工作方式。您可以使用 simpleJOIN来检索您的记录:

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

-检查您修改后的演示。如果你想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
于 2014-01-23T12:26:13.253 回答
0

Here's a similar solution...

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; 

http://sqlfiddle.com/#!2/bc532/1

于 2014-01-23T13:30:32.237 回答
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;

小提琴:http ://sqlfiddle.com/#!2/46d0b4/1/0

于 2014-01-23T13:17:01.687 回答