MySQL更新表的记录,引用同一个表的列

时间:2014-11-26 11:03:04

标签: mysql

我正在使用MySQL 5.6.17

我有一个self-referencing表格TableA,其中包含id (PK)title (varchar)type (varchar)parent_id (FK that refers to id of the same table)列。

样本数据如下:

id    title    type    parent_id
1     abc      G       NULL
2     def      G       NULL
3     xyz      G       NULL
4     pqr      G       NULL
5     abc      T       NULL
6     def      T       NULL
7     xyz      T       NULL
8     pqr      T       NULL

现在,我希望每个type='G'的记录都应该成为type='T' having the same title记录的子记录。

因此结果表数据应为:

id    title    type    parent_id
1     abc      G       5
2     def      G       6
3     xyz      G       7
4     pqr      G       8
5     abc      T       NULL
6     def      T       NULL
7     xyz      T       NULL
8     pqr      T       NULL

我在下面尝试过查询:

UPDATE TableA 
SET parent_id = (SELECT id FROM ( SELECT id FROM TableA WHERE TYPE='T' ) d)
WHERE TYPE='G';

但它返回

Error Code: 1242
Subquery returns more than 1 row

我也尝试过:

UPDATE TableA t1
SET t1.parent_id = t2.newlocalid
INNER JOIN (
    SELECT title, id AS newlocalid
    FROM TableA t2 
    WHERE  TYPE='T' 
) t2 ON t1.title = t2.title
WHERE t1.type='G'

但它也会在语法中返回错误。

任何人都可以帮助我实现它吗?

4 个答案:

答案 0 :(得分:1)

UPDATE TABLEA a 
JOIN TABLEA b ON a.title = b.title and a.type='G'and b.type='T'
SET a.parent_id = b.id

答案 1 :(得分:1)

这应该有效:

SELECT title, id AS newlocalid
INTO   #t2
FROM TableA     
WHERE  TYPE='T' 


UPDATE t1
SET t1.parent_id = t2.newlocalid
FROM TableA as t1
INNER JOIN  #t2 as t2 
ON t1.title = t2.title
WHERE t1.type='G'

答案 2 :(得分:0)

首先更新表列,您必须确定要设置的值。您不能使用多个值来更新同一语句中的单个列。

将您的sql更改为以下内容:

UPDATE TableA 
SET parent_id = (SELECT id FROM TableA WHERE TYPE='T' limit 0,1)// i mean make sure that it is returning single record not multiple.or better add some more where condition to get a single and required record without using limit
WHERE TYPE='G';

或某些特定条件:

 UPDATE TableA 
    SET parent_id = (SELECT id FROM TableA aa WHERE TYPE='T' and aa.type=TableA.type)
    WHERE TYPE='G';

答案 3 :(得分:0)

尝试:

UPDATE TableA a
SET parent_id = (SELECT id FROM TableA ref WHERE TYPE='T' AND ref.title=a.title)
WHERE TYPE='G';