the problem is:
I have two tables(column names are in brackets): Cars (CarColorId, CarName), CarColor (CarColorId, CarColorName);
The task is to UPDATE Cars.CarName with a string "_updated" but only if CarColor.CarColorName = 'red'. I have know idea how to do this without joins
I have tried this way:
UPDATE Cars set CarName = concat (CarName, '_updated') WHERE CarColorId = 1;
CarColorId = 1 = red; This request works, but the task is to use both tables
You can try any one of this in Oracle
Normal Update
UPDATE
CARS
SET
CARS.CARNAME =
CONCAT ( CARS.CARNAME,
'_updated' )
WHERE
EXISTS
(SELECT
CARCOLOR.CARCOLORID
FROM
CARCOLOR
WHERE
CARS.CARCOLORID = CARCOLOR.CARCOLORID
AND CARCOLOR.CARCOLORNAME = 'RED');
Using Inline View (If it is considered updateable by Oracle)
Note : If you face a non key preserved row error add an index to resolve the same to make it update-able
UPDATE
(SELECT
CARS.CARNAME AS OLD,
CONCAT ( CARS.CARNAME,
'_updated' )
AS NEW
FROM
CARS
INNER JOIN
CARCOLOR
ON CARS.CARCOLORID = CARCOLOR.CARCOLORID
WHERE
CARCOLOR.CARCOLORNAME = 'RED') T
SET
T.OLD = T.NEW;
Using Merge
MERGE INTO
CARS
USING
(SELECT
CARS.ROWID AS RID
FROM
CARS
INNER JOIN
CARCOLOR
ON CARS.CARCOLORID = CARCOLOR.CARCOLORID
WHERE
CARCOLOR.CARCOLORNAME = 'RED')
ON
( ROWID = RID )
WHEN MATCHED
THEN
UPDATE SET CARS.CARNAME =
CONCAT ( CARS.CARNAME,
'_updated' );
You can modify your query like this:
UPDATE
Cars
set
CarName = concat (CarName, '_updated')
WHERE
CarColorId in (
select
CarColorId
from
CarColor
where
CarColorName='red'
)
;
I know you said that you did not know how to do this without any joins. I don't know if that means you would prefer to avoid joins or whether you would be open to the possibility of using them if you could. If the latter is the case then check out this piece of code:
UPDATE
(
SELECT c.CarName, cc.CarColorName
FROM Cars c
INNER JOIN CarColors cc
ON c.CarColorId = cc.CarColorId
) CarsWithColor
SET CarsWithColor.CarName = CarsWithColor.CarName || '_Updated'
WHERE CarsWithColor.CarColorName = 'red';
Hope this helps also.
T
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.