MYSQL update if not exists else do nothing - mysql

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
)

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 - Unable to get all columns with select *

I have following 2 tables t1, t2
CREATE TABLE t1 (
id INT PRIMARY KEY
);
CREATE TABLE t2 (
id INT PRIMARY KEY
);
INSERT INTO t1 VALUES (1),(2),(3);
INSERT INTO t2 VALUES (2),(3),(4);
I am running
select * from t1 left join t2 using(id);
Result:
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
On running script:
select t1.id, t2.id from t1 left join t2 using(id);
Result:
+----+------+
| id | id |
+----+------+
| 1 | NULL |
| 2 | 2 |
| 3 | 3 |
+----+------+
select * is supposed to return all the columns, so, why I am not getting 2 rows when I am using select *?
Note: I am using Mysql
as doc says:
Natural joins and joins with USING, including outer join variants, are processed according to the SQL:2003 standard:
Redundant columns of a NATURAL join do not appear. Consider this set of statements:
CREATE TABLE t1 (i INT, j INT);
CREATE TABLE t2 (k INT, j INT);
INSERT INTO t1 VALUES(1, 1);
INSERT INTO t2 VALUES(1, 1);
SELECT * FROM t1 JOIN t2 USING (j);
column j is named in the USING clause and should appear only once in the output, not twice.
This is the normal behavior of the USING clause. Here's a quote from MySQL documentation:
Similarly, in the second SELECT statement, column j is named in the USING clause and should appear only once in the output, not twice.
(JOIN syntax)
And here's from Wikipedia:
[...] any columns mentioned in the USING list will appear only once, with an unqualified name, rather than once for each table in the join.
(JOIN (SQL)

result of selection is array and I want to use it to "where in" another selection

I have two tables (t1 & t2):
t1 (second column is array)
name | code
ee | 123, 124, 125
ef | 121, 123
______________________
t2
code_id | code_desc
121 | xxxxx
123 | yyyyyyy
124 | xxxxxxxx
if I do this query, all is ok:
SELECT * FROM t2 where code_id in (121,122)
but if I do this query I got NULL cell / result
SELECT * FROM t2 where code_id in (SELECT code FROM t1 where name = ee)
How can I get from one query all the info from two table?
Here is the code, I cant find a good sql online tool
CREATE TABLE t1 (name VARCHAR(200), codes VARCHAR(200));
CREATE TABLE t2 (codes_id VARCHAR(200), codes_desc VARCHAR(200));
INSERT INTO t1 (name, codes) VALUES ('ee', '123,124,125');
INSERT INTO t1 (name, codes) VALUES ('ef', '121,124');
INSERT INTO t1 (name, codes) VALUES ('eh', '123,124,125');
INSERT INTO t2 (codes_id, codes_desc) VALUES ('121', 'yyyyyyyyy');
INSERT INTO t2 (codes_id, codes_desc) VALUES ('122', 'xxxxxxxxx');
INSERT INTO t2 (codes_id, codes_desc) VALUES ('123', 'zzzzzzzzzzz');
SELECT * FROM t2 where code_id in (121,122)
SELECT * FROM t2 where code_id in (SELECT codes FROM t1 where name = 'ee')
You can use find_in_set function:
select *
from t2
where exists (
select 1
from t1
where name = 'ee'
and find_in_set(t2.code_id, t1.code) > 0
)
I'll advise you to normalize your table structure though. Because even though the above query is working, it is non-sargable.

Update table2 after update table1 in MySQL using Trigger

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 ;

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.