如果存在则更改不同的行或插入或删除

时间:2015-10-09 12:01:56

标签: sqlite

我有桌子:

CREATE TABLE tbl_teams (            
    id integer  primary key, 
    team_id varchar(80), 
    team_title varchar(80), 
    team_city varchar(80)
)
来自服务器的

来自一些活跃团队列表,例如以JSON格式:

{
    "teams":[
    {
            "team_id":678,
            "title":"Red Heads",
            "town":"Moscow"
    },
    {
            "team_id":90,
            "title":"Blue Hands",
            "town":"Baghdad"
    },
    {
            "team_id":128,
            "title":"White Tails",
            "town":"Paris"
    }
    ]} 

如何将表tbl_teams设置为实际状态?我的意思是,titletown可以更改,仅为常量team_id。如果表中不存在team_id,则可以更改或插入团队,如果服务器响应中不存在,则删除团队。

希望得到帮助。

1 个答案:

答案 0 :(得分:0)

来自其他论坛的回答:

UPDATE tbl_teams
    SET team_title=(SELECT title FROM NewTable WHERE 
             NewTable.team_id=tbl_teams.team_id), 
        team_city=(SELECT town FROM NewTable WHERE
             NewTable.team_id=tbl_teams.team_id)
    WHERE EXISTS(SELECT *
        FROM NewTable
             WHERE NewTable.team_id=tbl_teams.team_id and
                   (NewTable.title<>tbl_teams.team_title or
                    NewTable.town<>tbl_teams.team_city))

INSERT INTO tbl_teams (team_id,team_title,team_city)
    SELECT team_id,title,town
        FROM NewTable
            WHERE NOT EXISTS(SELECT * FROM tbl_teams WHERE
                 NewTable.team_id=tbl_teams.team_id)