简体   繁体   English

SQL根据另一个表中的ID更新特定行

[英]SQL Updating a particular rows based on the ID in another table

I have two tables 我有两张桌子

Price
RET_ID DBS_ID RRP

Database
DBS_ID PRO_ID

I would like to use UPDATE such that I can increase RRP in the Price table by 20% if the PRO_ID in the Database table is = 1 我想使用UPDATE,以便如果Database表中的PRO_ID = 1,则可以将Price表中的RRP提高20%

UPDATE
  ( SELECT RRP
    FROM PRICE
      JOIN database
        ON database.dbs_id = price.dbs_id
  )
SET rrp = 100
WHERE (database.pro_ID = 1);

I've been trying all manner of INNER JOIN ... ON to no avail. 我一直在尝试各种方式的INNER JOIN ... ON,但无济于事。 Thanks. 谢谢。

You can put the filtering condition in the where clause. 您可以将过滤条件放在where子句中。 Here is a method using exists : 这是一个使用exists的方法:

update price p
    set rpr = rpr * 1.2
    where exists (select 1
                  from database d
                  where d.dbs_id = p.dbs_id and d.pro_id = 1
                 );

Here is another way using in : 这是in另一种使用方式:

update price p
    set rpr = rpr * 1.2
    where p.dbs_id in (select d.dbs_id
                       from database d
                       where d.pro_id = 1
                      );
    UPDATE Price P SET RRP = RRP*1.2
 WHERE EXISTS 
(select  1 from Database 
where DBS_ID = P.DBS_ID AND PRO_ID = 1);


You can use this query 您可以使用此查询

MERGE INTO PRICE P 
 USING DATABASE D ON
(P.DBS_ID=D.DBS_ID) AND
D.PRO_ID=1
WHEN MATCHED
THEN
UPDATE SET
P.RRP=P.RRP*1.2;

When you are updating table from another table, always use MERGE function which is an amazing concept in SQL 从另一个表更新表时,请始终使用MERGE函数,这在SQL中是一个很棒的概念

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM