Update field from one table to another if exist, else null - ms-access

I have two tables(Columns) Employee(ID, EmployeeName, FK_DepartmentID) And Department(ID, DepartmentName) where my Employee table holds the Data of employee and set the foreign key of the department. Relational DB Department Table Employee Table
Now in my VB Code where I have an Employee Name textbox, and a combobox for the department from where users can update the Employee name and department. So I want to update Employee Table's Name as well as Foreign Key of the department so I used:
UPDATE Employee e, (SELECT d.ID FROM Department d Where d.DepartmentName = #dept) As d
SET e.FK_Department = d.ID, e.EmployeeName = #name
WHERE ((e.ID)='3') ;
Which seems to work fine. But I want my combobox of the department to be optional. Where It can be not selected and if so the FK_Department in Employee table will be NULL. But if I run the query without any value for #dept, the query creates 0 new rows which make sense, as my (SELECT d.ID FROM Department d Where d.DepartmentName = #dept) returns nothing. What can I do to update the query to get the result?
I also have tried joining but not sure where to apply Where d.DpartmentName = #dept, tried Set e.FK_Department = IIF((Select ID From Department Where DepartmentName = #dept) Is Null, Null, Department.ID), but seems not working.
Side note: Not sure if my problem is Upsert. Because at the end I am updating Employee Table nevertheless, Or my thinking is wrong?
Your assistance would be life-saving if it's possible. Thank you in advance.

Use sub query as follows:
UPDATE Employee e
Set e.EmployeeName = #name,
e.FK_Department = coalesce((select d.ID FROM Department d Where d.DepartmentName = #dept),
e.FK_Department)
WHERE e.ID='3' ;

Related

Update values of one column with multiple values

There is a table and that table has a column with a name country and I need to change values at that column in one query instead of multiple queries.
In this query, I change any value with Egypt to be 1
UPDATE subscribers
SET country = 1 WHERE country = 'Egypt';
in this query, I change any value with Qatar to be 2
UPDATE subscribers
SET country = 2 WHERE country = 'Qatar';
Any help to make these two queries in one?
Consider:
UPDATE subscribers SET country =
CASE
WHEN country = "Egypt" THEN 1
WHEN country = "Qatar" THEN 2
ELSE country
END
;
Now imagine doing that expression for many more countries. Instead join to a table that 'maps' data association (a master table of country names). Join on CountryName fields and update destination table CountryName field with ID from 'mapping' table. Convert to number type field. Or play it safe and update to another field and when all looks good, delete the original field.
You can use a case expression in MySQL:
UPDATE subscribers
SET country = (CASE WHEN country = 'Egypt' THEN 1 ELSE 2 END)
WHERE country IN ('Egypt', 'Qatar');
However, I would recommend using a derived table:
UPDATE subscribers s JOIN
(SELECT 'Egypt' as country, '1' as new_country UNION ALL
SELECT 'Qatar' as country, '2' as new_country
) x
USING (country)
SET s.country = x.new_country;

MySQL select and match two tables and update column based on matched data

It seems difficult for me to thats why I need your help. So basically, I got two tables named xp_pn_resale and xp_guru_properties. What I need to do is update or set the column postal_code from table xp_pn_resale based from the data from another table. So here are my tables
My xp_pn_resale table, I wrote query like this in order to show you
SELECT postal_code,
block,
concat(block,' ', street_name) as address
FROM xp_pn_resale
where street_name like '%ANG MO KIO%';
And I get the result like this
As you can see, there are null values there and there are some postal_code that has values because I manually update them based on what I searched. I just want to automatically fill the postal_code from the query I got from other table.
Here is my xp_guru_properties table and I wrote query like this in order to show you
SELECT property_name as GURU_PROEPRTY_NAME,
property_type as GURU_PROPERTY_TYPE ,
JSON_UNQUOTE(JSON_EXTRACT(xp_guru_properties.json, '$.postcode') )as GURU_POSTCODE
FROM xp_guru_properties
where property_type like '%HDB%' AND property_name like '%ang mo kio%';
And the result is like this
xp_guru_properties got a column property_type which is a bit similar in the concatinated columns of block and street_name from other table I named it as GURU_PROPERTY_NAME.
As you can see, there is the virtual column named GURU_POSCODE. The values of that column is what I want to fill in the postal_code column from xp_pn_resale table. I was doing it manually to update the postal_code by doing
UPDATE xp_pn_resale
SET postal_code = 560110
WHERE street_name LIKE '%ANG MO KIO%'
AND block = 110
which is very tedious to me. Does anyone know how could I automatically update it based on the queries I showed ? Help will be appriciated.
EDIT: I wrote a JOIN query like this but this is for the record Lingkong Tiga which i manually filled all the postal_code
select distinct
JSON_UNQUOTE(json_extract(g.json, '$.postcode')) postcode,
JSON_UNQUOTE(json_extract(g.json, '$.name')) name,
JSON_UNQUOTE(json_extract(g.json, '$.streetnumber') )streetnumber,
p.block, p.street_name, p.postal_code
from xp_pn_resale p
inner join xp_guru_properties g
on g.property_name = concat(p.block, ' ', p.street_name)
where g.property_type like '%HDB%' AND g.property_name like '%Lengkong Tiga%'
I got result like this
Join the two tables and update.
UPDATE xp_pn_resale AS r
JOIN xp_guru_properties AS p ON concat(r.block,' ', r.street_name) = p.property_name
SET r.postal_code = JSON_UNQUOTE(JSON_EXTRACT(xp_guru_properties.json, '$.postcode') )
WHERE r.street_name like '%ANG MO KIO%'
AND p.property_type like '%HDB%' AND p.property_name like '%ang mo kio%'
AND r.postal_code IS NULL

UPDATE COALESCE query with null values

Definitely a basic question, but I couldn't find an example.
I'm writing a procedure which merges two rows into the good row. It moves all child rows' ids to being the correct one, replaces all NULL values with available values in the row being removed before finally deleting the 'bad' row.
What I have so far is this:
CREATE DEFINER=`danielv`#`%`
PROCEDURE `emp_merge`(IN `#core_emp_id` int, IN `#bad_emp_id` int)
BEGIN
UPDATE claim SET employee_id = #core_emp_id
WHERE employee_id = #bad_emp_id;
WITH bad_employee_values AS (
SELECT * FROM employee WHERE employee_id = #bad_emp_id
)
UPDATE employee SET
employee.employment_date = COALESCE(employee.employment_date, bad_employee_values.employment_date),
WHERE employee_id = #core_emp_id;
DELETE FROM employee WHERE employee_id = #bad_emp_id;
END
However, I'm getting non-descript error messages and I'm not sure why. I suspect there's an issue with how I'm handling my CTE and coalesce function, but I'm not sure where the gap in my understanding is.
In this statement :
WITH bad_employee_values AS (SELECT * FROM employee WHERE employee_id = #bad_emp_id)
UPDATE employee SET
employee.employment_date = COALESCE(employee.employment_date, bad_employee_values.employment_date),
WHERE employee_id = #core_emp_id;
You are defining CTE bad_employee_values but you are not using it in the UPDATE part of the query, hence you cannot access its columns : for MySQL, bad_employee_values.employment_date is unknown.
It looks like you could simply avoid a CTE here. You could just self-join the table, like so :
UPDATE employee e_core
INNER JOIN employee e_bad ON e_bad.employee_id = #bad_emp_id
SET e_core.employment_date = e_bad.employment_date,
WHERE employee_id = #core_emp_id AND e_core.employment_date IS NULL
This query will simply select the record identified by #core_emp_id, join it with the corresponding "bad" record, and copy the value of employment_date. The second condition in the WHERE clause prevents records whose employment_date is not null from being selected.

Complicated MySql Update Join Query

Have is an example of the problem I'm facing. The database tables are a little different than usual, but needed to be setup this way.
Items: id, order_id, other fields
Items_Drinks: id, drinks, other fields
Orders: id, other fields
Orders_Drinks: id, drinks, other fields
I need to have an update query that will update the Orders_Drinks table with the sum of the Items_Drinks drinks field that have the same order_id as Orders_Drinks id field.
Items: 1 1 ...
Items: 2 1 ...
Items_Drinks: 1 4 ...
Items_Drinks: 2 5 ...
Orders: 1 ...
Orders_Drinks: 1 9 ...
The Orders_Drinks is currently correct, but if I were to update Items_Drinks with id of 1 to 5, I would need an update command to get Orders_Drinks with id 1 to equal 10.
It would be best if the command would update every record of the Orders_Drinks.
I know my database is not typical, but it is needed for my application. This is because the Drinks table is not needed for all entries. The Drinks table has over 5000 fields in it, so if every record had these details the database would grow and slow for no real reason. Please do not tell me to restructure the database, this is needed.
I am currently using for loops in my C# program to do what I need, but having 1 command would save a ton of time!
Here is my best attempt, but it gives an error of "invalid group function".
update Orders_Drinks join Items on Items.order_id=Orders_Drinks.id join Items_Drinks on Items_Drinks.id=Items.id set Orders_Drinks.drinks=sum(Item_Drinks.drinks);
I think this is what you're wanting.
Edited:
UPDATE `Order_Drinks` a
SET a.`drinks` = (SELECT SUM(b.`drinks`) FROM `Items_Drinks` b INNER JOIN `Items` c ON (b.`id` = c.`id`) WHERE a.`id` = c.`order_id`)
That should give you a total of 9 for the Order_Drinks table for the row id of 1.
This is assuming that Orders.id == Orders_Drinks.id and that Items.id == Items_Drinks.id.
You need to do an aggregation. You can do this in the join part of the update statement:
update Orders_Drinks od join
(select i.order_id, sum(id.drinks) as sumdrinks
from Items i join
Items_Drinks id
on id.id = i.id
) iid
on iid.order_id = od.id
set od.drinks = iid.sumdrinks;
Something like this will return the id from the orders_drinks table, along with the current value of the drinks summary field, and a new summary value derived from the related items_drinks tables.
(Absent the name of the foreign key column, I've assumed the foreign key column names are of the pattern: "referenced_table_id" )
SELECT od.id
, od.drinks AS old_drinks
, IFNULL(td.tot_drinks,0) AS new_drinks
FROM orders_drinks od
LEFT
JOIN ( SELECT di.orders_drinks_id
, SUM(di.drinks) AS tot_drinks
FROM items_drinks di
GROUP BY di.orders_drinks_id
) td
ON td.orders_drinks_id = od.id
Once we have SELECT query written that gets the result we want, we can change it into an UPDATE statement. Just replace SELECT ... FROM with the UPDATE keyword, and add a SET clause, to assign/replace the value to the drinks column.
e.g.
UPDATE orders_drinks od
LEFT
JOIN ( SELECT di.orders_drinks_id
, SUM(di.drinks) AS tot_drinks
FROM items_drinks di
GROUP BY di.orders_drinks_id
) td
ON td.orders_drinks_id = od.id
SET od.drinks = IFNULL(td.tot_drinks,0)
(NOTE: the IFNULL function is optional. I just used it to substitute a value of zero whenever there are no matching rows in items_drinks found, or whenever the total is NULL.)
This will update all rows (that need to be updated) in the orders_drinks table. A WHERE clause could be added (after the SET clause), if you only wanted to update particular rows in orders_drinks, rather than all rows:
WHERE od.id = 1
Again, to get to this, first get a SELECT statement working to return the new value to be assigned to the column, along with the key of the table to be updated. Once that is working, convert it into an UPDATE statement, moving the expression that returns the new value down to a SET clause.

cross table update can't work

I tried many code (some from stackoverflow), none of them can work.
Here is the structure of my mysql database:
table hesk_tickets : id, name, email
table hesk_callers : empnum, email, dept
the name column in hesk_tickets references the employee number, as does the empnum in hesk_callers
At beginning there is no other employee info in hesk_tickets but name. I want to add more employee info into it to make it easy to callback.
Then I import an xls file containing employee info into a new table named hesk_calles. I want to update hesk_tickets columns like email on lines that match the employee number in hesk_callers.
I tried this:
UPDATE hesk_tickets t1, hesk_callers t2
SET t1.email = t2.email
WHERE t1.name = t2.empnum;
also tried
UPDATE hesk_tickets ht
JOIN hesk_callers hc ON ht.name = hc.empnum
SET ht.email = hc.email
0 row(s) affected.
there are 6000 records in hesk_tickets and 1000 records in hesk_callers.
any solution will be appreciated,thx.
Try executing
select count(*) from hesk_tickets ht join hesk_callers hc on ht.name = hc.empum
to verify you actually have some matching data to update. You'll probably find that query returns zero. If that returns a number greater than zero, then it means that your UPDATE query is affecting zero rows because the email addresses already match (and therefore don't need updating)