Pgsql、mySql连表更新

Table a:
    id   | 主键 
    code | 编码

Table b:
    id   | 主键 
    aId  | 关联a表id
    code | 编码
    name | 名称

例,a、b表一对一,更新a表的code为b表code:

MySQL:

UPDATE a JOIN b ON a.id = b.aId SET a.code=b.code;
通用语法:
UPDATE table1 inner/left/right join table2/(select columns from table3  
        [inner/left/right join on condition]  [where conditions]) as t3
ON condition
SET column1 = value1,column2 = value2,...
[WHERE conditions]; 

PgSQL:

方法1.

UPDATE a SET code=b.code FROM b where a.id = b.aId;

方法2.较为灵活

UPDATE  a
SET     code = b.code
FROM    (
        SELECT  a.id, b.aId, b.code
        FROM    a
                INNER JOIN b  ON a.id = b.aId
        ) AS tb
WHERE   a.id = tb.id

更多例子:

Table main:
    id   | 主键 
    code | 编码

Table detail:
    id   | 主键 
    aId  | 关联main表id

detail表详情数据通过aId关联main表,将detail表的aId修改为对应的main表中以A开头的code中的数字

UPDATE detail 
SET aId = cast( SUBSTRING( tbs.code, E'([0-9]+)' ) AS INT8 ) 
FROM
    (
        SELECT
            b.id,b.aId, a.code
        FROM
            detail b 
            INNER join main a on a.id = b.aId
        WHERE
            a.code LIKE 'A%'  
    ) as tbs
where detail.id =tbs.id
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。