How Could I Update a table with conditions from other table - sql

I Have the Table "Person" and the table "Fisica" which is the extention of "Person". Both tables are related by the field name Id, and I want to update the tables based on conditions that include both tables.
For example:
Tables:
Persona(Id, Name, Money)
Fisica(Id, LastName, Year)
With data:
Persona(1, X, 5)
Persona(2, A, 10)
Fisica(1, Y, 1990)
Fisica(2, B, 2000)
I want to set Persona.Name=some_Value, Fisica.LastName=other_Value and Fisica.Year=number when Persona.Name='X', so it results
Persona(1, some_Value, 5)
Persona(2, A, 10)
Fisica(1, other_Value, number)
Fisica(2, B, 2000)
I am working in Oracle

You can't update two tables with one statement. So you need two UPDATE statements.
So you have to update one, then the other. The question is, which one first?
It doesn't really matter, but if you update Persona first and change the name, then you have to use the new name when updating Fisica. Like this:
update Persona
set name = 'some_Value'
where name = 'current_Name'
;
update Fisica
set lastname = 'other_Value',
year = number
where id = (
select id
from Persona
where name = 'some_Value'
)
;
If you update Fisica first, you use the old value of name both times, like this:
update Fisica
set lastname = 'other_Value',
year = number
where id = (
select id
from Persona
where name = 'current_Value'
)
;
update Persona
set name = 'some_Value'
where name = 'current_Value'
;
note number has to be replaced with an actual numeric value.
Good coding practice would be to put both statements in the same transaction and commit only if they are both successful.

Though Oracle don't provide such functionality as compare to mysql where we can write query like this:
Update table1 t1, table2 t2 set t2.field2="ABC" where t1.id=t2.id
But you can update multiple tables using single query in Oracle for Views.
So create the view for the above two tables Persona, Fisica and write query as follows:
CREATE OR REPLACE FORCE VIEW "Persona_Fisica" ("PersonaID", "Name", "Money", "FisicaID", "Lastname", "Year") AS
select P.Id as PersonaID,
Name as Name,
Money as Money,
F.Id as FisicaID,
LastName as Lastname,
year as Year
from Persona P,
Fisica F
where P.ID=F.ID
/
Update Persona_Fisica set Name=some_Value, LastName=other_Value,Year=number were Name='X',

Related

inserting multiples values in one column

I have a question about SQL. I have created a table in SQL with only one column containing the name of two people (say John and Matt). Later I added a new column into the table with ALTER TABLE. This column will contain the surname of these people.
My question is, in case mmy table contained several people already is there a command to enter the surnames for all the people at once rather than writing one command for each person as in:
INSERT INTO table (Surname) VALUE (John's surname) and
INSERT INTO table (Surname) VALUE (Matt's surname) ?
Thanks in advance
P.D.
I tried something like:
UPDATE foo set Surname=("Parker","Walker") where Name =("John","Matt") but does not work
You want an update. Something like this:
update t
set surname = 'John'' surname'
where firstname = 'John';
You can do this separately for each name. Or use a case expression for multiple ones:
UPDATE foo
SET Surname = (CASE WHEN Name = 'John' THEN 'Parker'
WHEN Name = 'Matt' THEN 'Walker'
END)
WHERE Name IN ('John', 'Matt');

I'm trying to update a table with information based on another table

I have a table with a list of SSNs (not real ones) connected to houseIDs.
I need to update a specific SSN's houseid based on a given address.
I have another table with houseIDs connected to HouseAddresses.
Here is what I have so far:
update persons
set houseid = houses.houseid
from houses
where houses.houseaddress = 'Alma Street'
and persons.SSN = 675849512;
While this works, it doesn't update anything, and I know it should update one row.
I'm afraid I don't know where to go from here.
Try to use this
update persons
set persons.houseid = houses.houseid
from houses
where houses.houseaddress = 'Alma Street' and
persons.SSN = 675849512;
OR
update persons
set houseid = i.houseid
from (
select houseid,houseaddress
from houses) i
where i.houseaddress = 'Alma Street' and
persons.SSN = 675849512;
if you want to update your houseid from other table connected by address you should join tables by addresses
Look this
update persons
set houseid = (Select Top(1) houses.houseid from
from houses
where houses.houseaddress = persons.address
.....
);
TRY IN THIS WAY: Use JOIN for effective solution in the following way but in the below code I am taking SSN as the common column but you can replace it with one if different:
UPDATE p SET houseid = h.houseid
FROM persons p
INNER JOIN houses h ON h.SSN = p.SSN
AND h.houseaddress = 'Alma Street'
AND ----------
--------
You can add more conditions according to you requirement in AND or add WHERE clause if required.

Fill one column with data from one column in another table (randomly)

Let's say I have a table Geometry and another table Customer like this:
Geometry      Customer
City        ID    Location
----         --    --------
Berlin       1    (null)
Paris        2    (null)
London
Now I'd like to fill the column Location with data from the column City. "Randomly" would be nice but it doesn't matter at all.
I've tried
update Customer set Location = (select City from Geometry where rownum < 3);
but still getting this error: single-row subquery returns more than one row
UPDATE: I'd like to fill the whole column Location with one update statement. I'm using ORACLE. The result should look like this:
Customer
ID     Location
--      -------
1      Berlin
2      London
Does someone have any better idea?
Thank you very much!
SQL Server:
UPDATE
Customer
SET
Location = (SELECT TOP 1 City FROM Geometry ORDER BY NEWID());
Since you just want it to pick one record at "random", you need to specify the correct number of rows:
update Customer set Location = (select City from Geometry where rownum = 1);
But note that since the subquery is not correlated to the Customer at all, the subquery may be optimised to only run once, and the same (randomly chosen) City will probably be used to update all Locations.
I would do the following, create a trigger on customer:
CREATE OR REPLACE TRIGGER customer_location
BEFORE INSERT OR UPDATE OF location ON customer
FOR EACH ROW
WHEN (NVL(new.location, 'X') = 'X')
BEGIN
SELECT city INTO :new.location
FROM (
SELECT city FROM geometry
ORDER BY DBMS_RANDOM.VALUE
) WHERE rownum = 1;
END;
/
UPDATE customer SET location = 'X';
This will update the customers table with a matching, "random" location. The trigger will also produce a new "random" location when a record is INSERTed into customers - as long as the location to be inserted is 'X' or NULL. (This wouldn't be wise if you actually have a location X - plug in some other value there!)
It is very possible to write a stored procedure to do the same thing, but you would have to create a cursor to loop over all the rows of customers where location is NULL.
update customer set location =
(select city from (
select distinct c.id, g.city, dbms_random.value from customer c, geometry g
order by value, city, id
) randoms where randoms.id = customer.id and rownum=1);
distinct necessary if there were two equal random values for one id

Updating a table by referencing another table

I have a table CustPurchase (name, purchase) and another table CustID (id, name).
I altered the CustPurchase table to have an id field. Now, I want to populate this newly created field by referencing the customer ids from the CustID table, using:
UPDATE CustPurchase
SET CustPurchase.id = CustID.id
WHERE CustPurchase.name = CustID.name;
I keep getting syntax errors!
I believe you are after the useful UPDATE FROM syntax.
UPDATE CustPurchase SET id = CI.id
FROM
CustPurchase CP
inner join CustID CI on (CI.name = CP.name)
This might have to be the following:
UPDATE CustPurchase SET id = CI.id
FROM
CustID CI
WHERE
CI.name = CustPurchase.name
Sorry, I'm away from my Postgres machine; however, based upon the reference, it looks like this is allowable. The trouble is whether or not to include the source table in the from_list.
Joining by name is not an ideal choice, but this should work:
UPDATE custpurchase
SET id = (SELECT c.id
FROM CUSTID c
WHERE c.name = custpurchase.name)
The caveat is that if there's no match, the value attempting to be inserted would be NULL. Assuming the id column won't allow NULL but will allow duplicate values:
UPDATE custpurchase
SET id = (SELECT COALESCE(c.id, -99)
FROM CUSTID c
WHERE c.name = custpurchase.name)
COALESCE will return the first non-NULL value. Making this a value outside of what you'd normally expect will make it easier to isolate such records & deal with appropriately.
Otherwise, you'll have to do the updating "by hand", on a name by name basis, to correct instances that SQL could not.

How to get one common value from Database using UNION

2 records in above image are from Db, in above table Constraint are (SID and LINE_ITEM_ID),
SID and LINE_ITEM_ID both column are used to find a unique record.
My issues :
I am looking for a query it should fetch the recored from DB depending on conditions
if i search for PART_NUMBER = 'PAU43-IMB-P6'
1. it should fetch one record from DB if search for PART_NUMBER = 'PAU43-IMB-P6', no mater to which SID that item belong to if there is only one recored either under SID =1 or SID = 2.
2. it should fetch one record which is under SID = 2 only, from DB on search for PART_NUMBER = 'PAU43-IMB-P6', if there are 2 items one in SID=1 and other in SID=2.
i am looking for a query which will search for a given part_number depending on Both SID 1 and 2, and it should return value under SID =2 and it can return value under SID=1 only if the there are no records under SID=2 (query has to withstand a load of Million record search).
Thank you
Select *
from Table
where SID||LINE_ITEM_ID = (
select Max(SID)||Max(LINE_ITEM_ID)
from table
where PART_NUMBER = 'PAU43-IMB-P6'
);
If I understand correctly, for each considered LINE_ITEM_ID you want to return only the one with the largest value for SID. This is a common requirement and, as with most things in SQL, can be written in many different ways; the best performing will depend on many factors, not least of which is the SQL product you are using.
Here's one possible approach:
SELECT DISTINCT * -- use a column list
FROM YourTable AS T1
INNER JOIN (
SELECT T2.LINE_ITEM_ID,
MAX(T2.SID) AS max_SID
FROM YourTable AS T2
GROUP
BY T2.LINE_ITEM_ID
) AS DT1 (LINE_ITEM_ID, max_SID)
ON T1.LINE_ITEM_ID = DT1.LINE_ITEM_ID
AND T1.SID = DT1.max_SID;
That said, I don't recall seeing one that relies on the UNION relational operator. You could easily rewrite the above using the INTERSECT relational operator but it would be more verbose.
Well in my case it worked something like this:
select LINE_ITEM_ID,SID,price_1,part_number from (
(select LINE_ITEM_ID,SID,price_1,part_number from Table where SID = 2)
UNION
(select LINE_ITEM_ID,SID,price_1,part_number from Table SID = 1 and line_item_id NOT IN (select LINE_ITEM_ID,SID,price_1,part_number from Table SID = 2)))
This query solved my issue..........