SQLite使用选择更新同一表

时间:2018-09-23 16:32:01

标签: sql sqlite

我正在尝试基于表中的值更新表。

玩家治具

PlayerFId
FixtureFId
Availability
SelectedPosition

我要更新玩家ID相同的所有行,并从先前的灯具ID中获取值。

示例数据

PlayerFId Fixture FId Availability SelectedPosition
    1           1          N              2
    1           2          U              0
    2           1          A              3
    2           2          U              0

我想用FixtureId 1的相关PlayerFId数据更新FixtureFId 2的所有行。

最终结果

PlayerFId Fixture FId Availability SelectedPosition
        1           1          N              2
        1           2          N              2
        2           1          A              3
        2           2          N              3    

我尝试使用此SQL,但无法正确映射PlayerFId值

UPDATE player_fixture 
SET 
    Availability = (SELECT Availability FROM player_fixture WHERE FixtureFId = 1), 
    SelectedPosition = (SELECT SelectedPosition FROM player_fixture WHERE FixtureFId = 1) 
WHERE FixtureFId = 2

2 个答案:

答案 0 :(得分:1)

您需要在子查询的WHERE子句中包含玩家的ID,以使结果相互关联。

UPDATE player_fixture
       SET availability = (SELECT pf.availability
                                  FROM player_fixture pf
                                  WHERE pf.playerfid = player_fixture.playerfid
                                        AND pf.fixturefid = 1), 
           selectedposition = (SELECT pf.selectedposition
                                      FROM player_fixture pf
                                      WHERE pf.playerfid = player_fixture.playerfid
                                            AND pf.fixturefid = 1)
       WHERE fixturefid = 2;

db<>fiddle

答案 1 :(得分:1)

SQLite不允许更新join。但这确实允许您使用单个子查询更新多个列:

UPDATE player_fixture
       SET (availability, selectedposition) =
            (SELECT pf.availability, pf.selectedposition
             FROM player_fixture pf
             WHERE pf.playerfid = player_fixture.playerfid AND
                   pf.fixturefid = 1
            )
       WHERE fixturefid = 2;