Update table2 after update table1 in MySQL using Trigger - mysql

I'm tryin to do a trigger with mysql to update a table2 after update a table1, basically the logic of the operation is this one:
i have a table1 which have next fields:
idtable1
idtable2
units
next table is like this
idtable2
totalunits
so i need to update totalunits field of table2 with the sum of all units of table1 with same id of table2, by example:
lets say that table1 has these values:
idtable1 | idtable2 | units
___________________________
1 | 1 | 3
2 | 1 | 2
3 | 2 | 2
then my table2 should be
idtable2 | totalunits
________________________
1 | 5
2 | 2
i know maybe it's super easy but i can't find any solution, i already created a trigger but it's not working
update `table2`,`table1` set totalunits= sum(table1.units) where table2.idtable2=table1.idtable2

You can use below query:
UPDATE table2 t2 SET t2.`counts` = (SELECT SUM(t1 .`units`) FROM table1 t1 WHERE t1.`id2` = t2.`id2`);

With a trigger
DELIMITER $$
CREATE TRIGGER upd_units AFTER UPDATE ON table1
FOR EACH ROW
BEGIN
SET #diff := OLD.units - NEW.units;
UPDATE table2 SET total_units = total_units - #diff WHERE idtable2 = OLD.idtable2;
END;$$
DELIMITER ;

Related

How can I join two tables but only return rows that don't match specific column which include NULL as well?

I have two tables which look like this:
T1: ID | oldID
T2: ID | newID
I basically need to join these tables when their IDs match. However, I only want to return the results like: ID | oldID | newID where oldID do not equal to newID.
Example data:
T1: 1 | 100
2 | NULL
3 | 200
4 | 500
T2: 1 | NULL
2 | 300
3 | 200
4 | 400
My expected result:
T3: 1 | 100 | NULL
2 | NULL | 300
4 | 500 | 400
Can anyone point me on the right track?
Try this answer, Hope this helps
CREATE TABLE #T1 (ID INT, oldID INT)
INSERT INTO #T1 VALUES(1,100)
INSERT INTO #T1 VALUES(2,NULL)
INSERT INTO #T1 VALUES(3,200)
INSERT INTO #T1 VALUES(4,500)
CREATE TABLE #T2 (ID INT, [NewId] INT)
INSERT INTO #T2 VALUES(1,NULL)
INSERT INTO #T2 VALUES(2,300)
INSERT INTO #T2 VALUES(3,200)
INSERT INTO #T2 VALUES(4,400)
select T1.ID,T1.oldID,T2.[NewId]
FROM #T1 T1, #T2 T2
WHERE T1.id=T2.id and ISNULL(T1.oldID,0) != ISNULL(T2.[NewId],0)
DROP TABLE #T1
DROP TABLE #T2
For SQL Server
SELECT T1.ID ,T1.oldID,T2.[newID]
FROM T1
INNER JOIN T2 ON T1.ID = T2.ID AND ISNULL(T1.oldID,0) <> ISNULL(T2.[newID],0)
For MySql, use IFNULL instead of ISNULL.
If zero(0) is a value in either oldID or newID, you can use any other unused values for ISNULL function(ie -1 )
select t1.ID,t1.oldID,t2.NewId
FROM T1 t1, T2 t2
WHERE t1.ID=t2.ID
AND COALESCE(t1.oldID,0) <> COALESCE(t2.NewId,0)
Explanation
select t1.ID,t1.oldID,t2.NewId
FROM T1 t1, T2 t2
WHERE t1.ID=t2.ID #IDs are equal in two tables
AND t1.oldID <> t2.NewId
Result is:
# ID, oldID, NewId
'4', '500', '400'
If you check like this, you will not get the result as you expected, the reason is NULL value not handled properly.
But If you use COALESE means it will check as below:
COALESCE(value1,value2,value3,...)
The above syntax is equivalent to the following IF-THEN-ELSE statement
IF value1 is not NULL THEN
result = value1;
ELSIF value2 is not NULL THEN
result = value2;
ELSIF value3 is not NULL THEN
result = value3;
ELSE
result = NULL;
END IF;
Example:
SELECT COALESCE(NULL, 2, 3); Returns 2
So In our Query,COALESCE(t1.oldID,0) will return 0 if the t1.oldID is null..
select t1.ID,t1.oldID,t2.NewId
FROM T1 t1, T2 t2
WHERE t1.ID=t2.ID
AND COALESCE(t1.oldID,0) <> COALESCE(t2.NewId,0)

MYSQL Updating row to maximum value of similar rows

I have a table like this in MYSQL:
ID | NAME | VALUE |
----------------------------
1 | Bob | 1 |
2 | Bob | 2 |
3 | Jack | 5 |
4 | Jack | 8 |
5 | Jack | 10 |
and I'm trying to update the VALUE column to the highest value of rows with same NAME. So the result should be:
ID | NAME | VALUE |
----------------------------
1 | Bob | 2 |
2 | Bob | 2 |
3 | Jack | 10 |
4 | Jack | 10 |
5 | Jack | 10 |
I managed to get the max value like this:
SELECT MAX(Value) max FROM `table` GROUP BY Name having count(*) >1 AND MAX(Value) != MIN(Value)
But can't figure out how to put it in my update
Update table set Value = (SELECT MAX(Value) max FROM `table` GROUP BY Name having count(*) >1 AND MAX(Value) != MIN(Value))
Doesn't work. I'd appreciate any help.
This is easier than other answers are making it.
UPDATE MyTable AS t1 INNER JOIN MyTable AS t2 USING (Name)
SET Value = GREATEST(t1.Value, t2.Value);
You don't have to find the largest value. You just have to join each row to the set of rows with the same name, and set the Value to the greater Value of the two joined rows. This is a no-op on some rows, but it will apply to every row in turn.
http://sqlfiddle.com/#!9/f79a3/1
UPDATE t1
INNER JOIN (SELECT name, MAX(`value`) max_value
FROM t1 GROUP BY name) t2
ON t1.name = t2.name
SET t1.value = t2.max_value;
Create a temporary table consisting of ID NAME and MAX VALUE as follows:
CREATE TEMP TABLE TABLE1 AS
(SELECT NAME,MAX(Value) value FROM `table` GROUP BY Name having count(*) >1
AND MAX(Value) != MIN(Value)
);
Use this temporary table to do your update as follows:
UPDATE
Table_A
SET
Table_A.value = Table_B.value
FROM
`table` AS Table_A
INNER JOIN TABLE1 AS Table_B
ON Table_A.NAME = Table_B.NAME
Also this code is somewhat of an approximation as i am not familiar with mysql but i am familiar with sql.
Let me know if this doesn't help.
Simple left join would do the trick.
Try this out and let me know in case of any queries.
select a.id,a.name,b.value
from
table a
left join
(select name,max(value) as value from table group by name) b
on a.name=b.name;
You may use this query. The table is joined with a subquery (table t2) that contains the results you want to update your table with:
UPDATE `table` t1,
(SELECT Name, MAX(Value) maxv, MIN(Value) minv
FROM `table`
GROUP BY Name
HAVING COUNT(*)>1 AND maxv != minv) t2
SET t1.Value = t2.maxv
WHERE t1.Name = t2.Name;
If you want to know how will the values be updated, you can first run an equivalent SELECT query:
SELECT t1.*, t2.maxv
FROM `table` t1,
(SELECT Name, MAX(Value) maxv, MIN(Value) minv
FROM `table`
GROUP BY Name
HAVING COUNT(*)>1 AND maxv != minv) t2
WHERE t1.Name = t2.Name;
This query will display all the fields of table, followed by the new value maxv. You can check the current value and the new value, and if it looks fine, you may run the UPDATE query.

Compare two tables and Insert/Update data

I have two tables as below what i need to do is
Loop through Table2 rows and need to check if table1ID in Table2 exists in table1. If exists update existing table1 row active flag to 0 and insert a new record in table1 with values from Table2 row. If does not exist insert a new record in table1 with values from Table2 row. We can assume E1, E2,E3 columns correspond to Q1A, Q2A, Q3A in table1.
Table1:
Table1ID Q1A Q2A Q3A Active
1 2 Test 1 1
2 3 Test2 1 1
3 4 Test3 1 1
4 5 Test4 1 1
Table2:
Table1ID E1 E2 E3
1 2 TestData1 1
2 3 TestData2 1
3 4 TestData3 1
5 5 TestData5 1
6 7 TestData6 0
If exists
update existing table1 row active flag to 0
and
insert a new record in table1 with values from Table2 row.
If does not exist insert a new record in table1 with values from Table2 row
From what you wrote, it seems you want to update the Active column to 0 for an existing record and insert the records from Table2 in any case.
Below should work for you:
MERGE Table1 t1
USING Table2 t2
ON t1.Table1ID = t2.Table1ID
WHEN MATCHED THEN
UPDATE
SET t1.Active = 0;
INSERT (Table1ID, Q1A, Q2A, Q3A, Active)
VALUES (t2.Table1ID, E1, E2, E3, 1);
So in both cases, if the record exists, you're going to insert a row from Table2. The only difference is, if it exists in Table1, you want to set it to zero.
DECLARE #currid INT, #maxid INT, #lastid INT
SELECT #currid = 0
, #lastid = 0
, #maxid = MAX(Table1ID)
FROM Table2
WHILE (#currid < #maxid)
BEGIN
-- Get the next minimum Table1ID from Table2
SELECT #currid = MIN(Table1ID)
FROM Table2
WHERE Table1ID > #lastid
-- See if it exists in Table1
IF EXISTS (SELECT 1 FROM Table1 WHERE Table1ID = #currid)
BEGIN
-- Set Active to zero as specified
UPDATE Table1ID
SET Active = 0
WHERE Table1ID = #currid
END
-- Copy row from Table2 - I assume with all columns as well as 1 for Active
INSERT INTO Table1
SELECT *, 1
FROM Table2
WHERE Table1ID = #currid
-- Set our ID value for the next loop
SET #lastid = #currid
END

MYSQL update if not exists else do nothing

My question is how do i update a value in a table if it does not exists on another table.I checked INSERT ... ON DUPLICATE KEY UPDATE
but it describes about inserting something which updates and not insert.
My situation is like, i have two tables say (t1,t2). I want to update a column in t1 with a value if its not present in t2. Otherwise increment the value and try the update again.
So i want something like
update t1 set column = 'value' if it does not exists in t2
Can somebody suggest a solution
Here is a way to do it using the JOIN.
create table tab1 (id int , val int);
insert into tab1 values (1,1),(2,3),(3,5);
create table tab2 (id int , val int);
insert into tab2 values (4,1),(2,3),(3,5);
In the above tab1 (id = 1) not available in tab2 and using the following command we can update such values
update tab1 t1
left join tab2 t2 on t1.id = t2.id
set t1.val =
case
when t2.id IS NULL then 8
else t1.val
end
The output after the update command will look like
mysql> select * from tab1 ;
+------+------+
| id | val |
+------+------+
| 1 | 8 |
| 2 | 3 |
| 3 | 5 |
+------+------+
Also you can use EXIST which is also pretty better than doing left join
update tab1 t1 set t1.val = 10
where NOT EXISTS
(
select 1
from tab2 where tab2.id = t1.id
)

Mysql Update based on existence in other table

I'm trying to figure out how to mass update a mysql table based on if a value exists in a column in another table.
e.g. pseudo code:
if Table1.`col`=Table2.`col` then
Update Table1.`status`=1
or
if table2.`col` exists in table1.`col`
Update Table1.`status`=1
What's the best way to achieve this?
Try this one -
UPDATE table1 t1
JOIN table2 t2
ON t1.col = t2.col
SET t1.status = 1;
Table 1
col | status
-------------
jaga | 0
kala | 0
Table 2
col | status
--------------
jaga | 1
latha | 0
If Table1.col=Table2.col // So this point is fullfill jaga record.
then Update Table1.status=1 // So Table 1 jaga row status want to Update in 1.
Is I am Correct?.
Then Try
UPDATE Table1 AS t1, Table2 AS t2 SET t1.col = 1 WHERE t1.col = t2.col
Happy Codings,
update t_checkout A
INNER JOIN t_target B on A.Media_ID = B.Media_ID
set A.status = 'R'
where A.Media_ID = 45
and exists (select * from t_target where B.Media_ID = 45 and status = 'R');
The 45 is hard coded here, but the value actually comes from a php parameter.