4

I have searched and found loads of examples but am still struggling to make this work.

I have the following table in SQLite:

SELECT * FROM TableA;

ID|USER|NAME|PARENT
1|User1|SomeName|-1
2|User1|SomeOtherName|1
3|User2|SomeName|-1
4|User2|SomeOtherName|-1

The PARENT for ID 2 with NAME of SomeOtherName is ID 1 - This is correct.

The PARENT for ID 4 with the NAME of SomeOtherName is ID -1 - This is incorrect. It should be ID 3.

I have many incorrect records like that (all with the same NAME of SomeOtherName and a PARENT of -1).

The column that ties them together is USER.

I need to update all the incorrect records with the correct parent ID.

I have tried the following to no avail:

DROP TABLE orphans;

CREATE TEMP TABLE orphans as
    SELECT TableA.id, TableA.user, TableA.name FROM TableA WHERE TableA.name = 'SomeOtherName' AND TableA.parent = -1;

UPDATE TableA
SET parent = (  SELECT TableA.id
                        FROM TableA
                        INNER JOIN orphans
                        ON TableA.name = 'SomeName' AND orphans.user = TableA.user
                )
WHERE TableA.user IN (  SELECT TableA.user
                                FROM TableA WHERE TableA.name = 'SomeOtherName' AND TableA.parent = -1 )
;

I just can't seem to get it right. Any help will be appreciated.

4

2 回答 2

2

据我所知,sqlite对于语句中的复杂查询的能力非常有限。UPDATE您不能使用多个表,而且我还没有找到从子查询中引用当前行中的值的方法。

相反,我想出了这个:

SELECT id, user, name,
  CASE name = 'SomeOtherName' AND parent = -1
  WHEN 1 THEN (
    SELECT MAX(id)
    FROM TableA A2
    WHERE A1.user = A2.user
    AND A2.name != 'SomeOtherName'
  ) ELSE parent END AS parent
FROM TableA A1;

应该是你想要的数据,对吧?您可以将其写入临时表,然后从那里将数据反馈回原始表。REPLACE如果您有唯一的键,则可以使用此反馈来完成,如果没有,则使用DETELTE后跟INSERT。我在 sqlfiddle 创建了后者的示例

于 2012-08-09T13:24:26.030 回答
1

当然迟到的答复,但我相信这可以在没有临时表的情况下完成。只需以正确的方式使用选择。下面的代码在类似的表格中适用于我:

UPDATE TableA SET PARENT = (
            SELECT ID
            FROM TableA AS T
            WHERE T.NAME = 'SomeName' AND T.USER = TableA.USER
        )
WHERE ID IN (
            SELECT ID
            FROM TableA
            WHERE TableA.NAME = 'SomeOtherName' AND TableA.PARENT = -1
            );
于 2015-03-18T09:35:17.003 回答