postgresql 如何在SQL中建立PK和FK的连接?

utugiqy6  于 2022-12-22  发布在  PostgreSQL
关注(0)|答案(2)|浏览(261)

我需要把一个表的PK连接到另一个表的FK,这是我的数据库:

我只有case表中的case_id,而对于此SQL语句,我需要case_test表中的case_uid

UPDATE case_test (this part is ok)
SET country = 'Canada' (this part is ok)
WHERE case_test.case_uid = case.case_uid  (is the same as case_uid from the case table but i only know the case_id field from that table)

我知道我只知道case_id,如何在键之间建立连接?

bwitn5fc

bwitn5fc1#

使用标量子查询从表case中提取case_uid

update case_test
set country = 'Canada'
where case_uid = (select case_uid from "case" where case_id = ?);

顺便问一下,表case中的case_id是否有多个case_uid?如果是这样,则子查询不再是标量,where子句应使用in运算符而不是=

where case_uid in (select case_uid from "case" where case_id = ?)

不相关,但case不是表的正确名称。

j1dl9f46

j1dl9f462#

免责声明:使用风险自负!请确保在执行下面的UPDATE语句之前有备份。在应用更新之前,请检查内部EXISTS SELECT语句。

UPDATE
    case_test
SET
    country = 'Canada'
WHERE 
    EXISTS (
        SELECT
            ct2.case_test_id  /* EXISTS function returns TRUE if any row is returned, so you can use any column or literal value in SELECT body */
        FROM
            case_test AS ct2 /* you need to give an alias inside EXISTS function to not conflicts with the UPDATE table name */
            INNER JOIN
            case AS c2 /* The same here for an alias */
                ON  c2.case_uid = ct2.case_uid
        WHERE
            ct2.case_uid = case_test.case_uid  /* Here the link between the PK of outer case_test table from UPDATE and case_test (as ct2) inside this EXISTS function */
            AND c2.case_id = ? /* Here you set your case_id know value */
    )

相关问题