update only null value columns in table if ID exits in table - mysql

I am trying to check for the ID. If it does not exist I want my data to be inserted as a new record in table and if ID exists I want to compare both incoming new record and existing record and only update the values which are null in existing record. I have written the query but I don't know how to check for null in each column:
Here is the query:
insert into ui_table(MDMID,FirstName,Lastname,Mail,Address,City,State,Zip,ProfileStatus,TAID)
select im.MDMID,im.FirstName,im.Lastname,im.Mail,im.Address,im.City,im.State,im.Zip,im.ProfileStatus,im.TAID
from intermediate im on duplicate key update
MDMID = im.MDMID,
FirstName = im.FirstName,
Lastname = im.Lastname,
Mail = im.Mail,
Address = im.Address,
City = im.City,
State = im.State,
Zip = im.Zip,
ProfileStatus = im.ProfileStatus,
TAID = im.TAID;

Related

How to Copy one table data to another table with 2 wherecondtion and an if condtion MYSQL

Actually i want to copy one tables data to another table. it has no unique id , the only relation between two are a "fra" number and a 'pra' number but both are not unique . but fra and pra (r concatenate ) is unique for each. and one table data is sex (customer table) and another is gender(new_customer table) the gender is Boolean, sex is string of m and f . how can i copy from customer table to new_customer table
I tried these way
UPDATE new_customer JOIN customer
SET registrations.name = customer.nam,
registrations.surname = customer.vornam,
registrations.ort = .ort,
registrations.phone = customer.telmbl,
registrations.surname = customer.vornam
WHERE registrations.fra = customer.fra
and registrations.pra = customer.pra;
Any body to help me?
something like following, you can try.
UPDATE new_customer AS new_c, customer AS old_c
SET
new_c.name = old_c.nam,
new_c.surname = old_c.vornam,
new_c.ort = old_c.ort,
new_c.phone = old_c.telmbl
WHERE
new_c.fra = old_c.fra
AND new_c.pra = old_c.pra;

Preventing duplicate entry in database before inserting value into database

I am trying to check the database to see if the activity Name that I am entering already exists, if it exists I should get an error if it don't it should go ahead and insert values into database, below is the code I am trying but it isn't working properly btw the prevention of duplicates is already working cause of the UNIQUE KEY i give to activity Name but I also want an alert to let the users know that the activity name already exists.
function insertQueryDB(tx) {
var myDB = window.openDatabase("test", "1.0", "Test DB", 1000000);
tx.executeSql('CREATE TABLE IF NOT EXISTS dataEntryTb (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, activityName TEXT NOT NULL UNIQUE, location TEXT NOT NULL, time NOT NULL, date NOT NULL, reporter NOT NULL)');
var an = document.forms["myForm"]["activityName"].value;
var l = document.forms["myForm"]["location"].value;
var t = document.forms["myForm"]["time"].value;
var d = document.forms["myForm"]["date"].value;
var r = document.forms["myForm"]["reporter"].value;
if('COUNT activityName FROM dataEntryTb WHERE EXISTS activityName = "'+an+'" '){
navigator.notification.alert("activityName already Exists");
}
var query = 'INSERT INTO dataEntryTb ( activityName, location, time, date, reporter) VALUES ( "'+an+'", "'+l+'", "'+t+'", "'+d+'", "'+r+'")';
tx.executeSql(query,[]);
navigator.notification.alert("Retrieved the following: Activity Name="+an+" and Location="+l);
}
I think all you need to do is establish an unique key on activityName...
alter table dataEntryTb add unique key (activityName);

MYSQL insert an an new duplicate entry but with a few different defined fields

Presently I am inserting a new entry (copying the data from an existing entry) & then updating this new entry. eg:
$age = 30;
INSERT INTO table (category,sex,age) SELECT category,sex,age FROM table WHERE id = $id
<br>$new_id = mysql_insert_id();
<br>UPDATE sample_table SET age = $age WHERE id = $new_id
However, I would like to save a database interaction by inserting the new entry in one go (without having to get mysql_insert_id / updating the new entry). eg:
$age = 30;
INSERT INTO table (category,sex,$age) SELECT category,sex FROM table WHERE id = $id
Is there a way to insert the above by explicitly defining the age field, or is there another MYSQL command I should be using?
You are looking for this:
INSERT INTO table (category, sex, age)
SELECT category, sex, $age
FROM table
WHERE id = $id ;
You can put constants in the select list.

UPDATE multiple rows with different values in one query in MySQL

I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand.
For instance, three updates into 1 query:
UPDATE table_users
SET cod_user = '622057'
, date = '12082014'
WHERE user_rol = 'student'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '2913659'
, date = '12082014'
WHERE user_rol = 'assistant'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '6160230'
, date = '12082014'
WHERE user_rol = 'admin'
AND cod_office = '17389551';
I read an example, but I really don't understand how to make the query. i.e:
UPDATE table_to_update
SET cod_user= IF(cod_office = '17389551','622057','2913659','6160230')
,date = IF(cod_office = '17389551','12082014')
WHERE ?? IN (??) ;
I'm not entirely clear how to do the query if there are multiple condition in the WHERE and in the IF condition..any ideas?
You can do it this way:
UPDATE table_users
SET cod_user = (case when user_role = 'student' then '622057'
when user_role = 'assistant' then '2913659'
when user_role = 'admin' then '6160230'
end),
date = '12082014'
WHERE user_role in ('student', 'assistant', 'admin') AND
cod_office = '17389551';
I don't understand your date format. Dates should be stored in the database using native date and time types.
MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
cod_user=VALUES(cod_user), date=VALUES(date)
This assumes that the user_rol, cod_office combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list.
If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.
However, this approach makes prepared statements easier to build and more concise.
UPDATE table_name
SET cod_user =
CASE
WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END, date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
You can use a CASE statement to handle multiple if/then scenarios:
UPDATE table_to_update
SET cod_user= CASE WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END
,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
To Extend on #Trevedhek answer,
In case the update has to be done with non-unique keys, 4 queries will be need
NOTE: This is not transaction-safe
This can be done using a temp table.
Step 1: Create a temp table keys and the columns you want to update
CREATE TEMPORARY TABLE temp_table_users
(
cod_user varchar(50)
, date varchar(50)
, user_rol varchar(50)
, cod_office varchar(50)
) ENGINE=MEMORY
Step 2: Insert the values into the temp table
Step 3: Update the original table
UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET
t1.cod_office = tt1.cod_office
t1.date = tt1.date
Step 4: Drop the temp table
In php, you use multi_query method of mysqli instance.
$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";
$mysqli->multi_query($sql);
comparing result to transaction, insert, case methods in update 30,000 raw.
Transaction: 5.5194580554962
Insert: 0.20669293403625
Case: 16.474853992462
Multi: 0.0412278175354
As you can see, multiple statements query is more efficient than the highest answer.
Just in case if you get error message like this:
PHP Warning: Error while sending SET_OPTION packet
You may need to increase the max_allowed_packet in mysql config file.
UPDATE Table1 SET col1= col2 FROM (SELECT col2, col3 FROM Table2) as newTbl WHERE col4= col3
Here col4 & col1 are in Table1. col2 & col3 are in Table2 I Am trying to update each col1 where col4 = col3 different value for each row
I did it this way:
<update id="updateSettings" parameterType="PushSettings">
<foreach collection="settings" item="setting">
UPDATE push_setting SET status = #{setting.status}
WHERE type = #{setting.type} AND user_id = #{userId};
</foreach>
</update>
where PushSettings is
public class PushSettings {
private List<PushSetting> settings;
private String userId;
}
it works fine

Update table using alias

I need to fill some fields in a table getting informations from other records of the same table.
I tried to write a query to explain what I want to do:
update globale2
set
nita = t.nita,
tita = t.tita,
notaita = t.notaita
where
neng = t.neng and
nita is null
(select nita, neng, tita, notaita from globale where uris='mma' and nita is not null) as t
edit to eplain better:
every records have these fields: "nita", "tita", "notaita", "neng" ("neng" cannot be null)
I want to fill these fields: "nita", "tita", "notaita" (where "nita" is empty)
with the same values from another record where "neng" equals the other "neng"
You can however, join the two tables.
UPDATE globale2 g
INNER JOIN globale gg
ON g.neng = gg.neng
SET g.nita = gg.nita,
g.tita = gg.tita,
g.notaita = gg.notaita
WHERE g.nita IS NULL
AND gg.uris = 'mma'
AND gg.nita IS NOT NULL
assume there is a table A_temp, with two columns 'one' and 'two'.
TABLE A_temp
ONE TWO
1 2
this is the present status of the table.
The query
UPDATE (SELECT * FROM A_temp ) A SET one = A.two where one = '1'
updates the table as
ONE TWO
2 2
Hope you get the idea and that it helps..