Display column name of most recently updated column - mysql

I am wondering if it is possible to display the column name of the most recently updated column in a table.
Example:
**Original Record created on 03/20/14:**
Name: John
Height
Weight
Age
Update_date: 03/20/14
Update_Column: Name
Then someone comes in and updates the height on 03/22/14:
Name: John
Height: 5'9
Weight
Age
Update_date: 03/22/14
Update_Column: Height
And the Update_date and Update_column would change again if someone came in and put a value for age. And so on.
Is this possible?
Also, if the above is possible, would it be possible to display the column name farthest right if a user updated more than one column at the same time?
Example:
User updates the below record:
Name: John
Height: 5'9
Weight
Age
Update_date: 03/22/14
Update_Column: Height
And adds in a weight and age at the same time on 03/24/14:
Name: John
Height: 5'9
Weight: 150
Age: 31
Update_date: 03/22/14
Update_Column: Height
The Update_Column would display Age because it is the farthest to the right. (Thinking of it as you read from left to right, so the column that was last updated would be the one farthest right)
So to sum things up, I need to be able to display Updated_date(which will be the current date when the record is last updated) and Updated_Col (which is the column name of the last column that was updated, and if multiple columns are updated then display the one that a value was updated last in)
Hopefully the examples help to clarify things.
Thanks,
Steven

You need to store those meta data for each row. So you'd need two new columns, the update_date and update_column. Then you can add an before update trigger to check which columns are about to change and set the update date.
update
Here's an example:
delimiter //
create table a (
id int (10) unsigned auto_increment,
a int(10),
b int(10),
update_date datetime NULL,
update_column varchar(16) NULL,
primary key (id)
)//
create trigger bu_a before update on a for each row begin
set NEW.update_date = NOW();
set NEW.update_column = NULL;
-- you need to start with the rightmost column if you want
-- that matched with the highest priority
if OLD.b != NEW.b then
set NEW.update_column = "b";
elseif OLD.a != NEW.a then
set NEW.update_column = "a";
end if;
end //
Test:
insert into a (id,a,b) values (1,1,1), (2,1,1), (3,1,1), (4,1,1)[
update a set b = 2 where id = 2;
update a set a = 2 where id = 3;
update a set a = 2 where id = 4;
update a set b = 2 where id = 4;
select * from a;
Output:
ID A B UPDATE_DATE UPDATE_COLUMN
1 1 1 (null) (null)
2 1 2 March, 24 2014 23:22:33+0000 b
3 2 1 March, 24 2014 23:22:33+0000 a
4 2 2 March, 24 2014 23:22:33+0000 b

Related

MySQL Trigger Setting All Other Values to NULL When Run

I have two tables, Accounts and Person:
CREATE TABLE Person(
id INT NOT NULL PRIMARY KEY,
Person_Name VARCHAR(17) NOT NULL,
P_Location INT NOT NULL
);
INSERT INTO Person VALUES (1,"Adam",300),(2,"Betty",10),(3,"Louis",60);
CREATE TABLE Accounts(
Person_id INT PRIMARY KEY,
Balance INT DEFAULT 200);
INSERT INTO Accounts VALUES (1,2000),(2,1350),(3,800);
And one trigger, Bonuses:
CREATE TRIGGER Bonuses
AFTER UPDATE ON Person
FOR EACH ROW
UPDATE Accounts
SET Balance = CASE WHEN (SELECT P_Location FROM Person WHERE id = Person_id) = 3 THEN Balance - 150
WHEN (SELECT P_Location FROM Person WHERE id = Person_id) = 7 THEN Balance + 100
WHEN (SELECT P_Location FROM Person WHERE id = Person_id) = 15 THEN Balance - 30
WHEN (SELECT P_Location FROM Person WHERE id = Person_id) = 1 THEN Balance + 200
END;
And I want to make the trigger update the Accounts table according to certain instructions whenever the P_Location on the Person table changes to one of a select few values (3,7,15 and 1). However, as things are they result is incorrect. Assume I run the above code, the tables I get are:
Person
id
Player_Name
P_Location
1
Adam
300
2
Betty
10
3
Louis
60
Accounts
Person_id
Balance
1
2000
2
1350
3
800
Now if I run UPDATE Person SET P_Location = 3 WHERE id = 1; then the Accounts table should yield:
Person_id
Balance
1
1850
2
1350
3
800
However, what I get is
Person_id
Balance
1
1850
2
NULL
3
NULL
Any idea of what I'm doing wrong?
Well, that code did exactly what you said, though it wasn't what you meant!
That's the thing about UPDATE queries, EVERY row will get an update unless a WHERE clause is used to filter what actually gets modified. Nothing is found from the CASE with most records, so any of those will get assigned to NULL. To see this behavior, check this fiddle example.
However, there is good news, all that is needed in the trigger is to add a WHERE clause. Note that I simplified the CASE handling make use of the UPDATE trigger's NEW references:
CREATE TRIGGER Bonuses
AFTER UPDATE ON Person
FOR EACH ROW
UPDATE Accounts
SET Balance = CASE WHEN NEW.P_Location = 3 THEN Balance - 150
WHEN NEW.P_Location = 7 THEN Balance + 100
WHEN NEW.P_Location = 15 THEN Balance - 30
WHEN NEW.P_Location = 1 THEN Balance + 200
END
WHERE Person_id = NEW.id;
So starting with:
Then run: UPDATE Person SET P_Location = 3 WHERE id = 1;
Gives:
Example fiddle with your tables, the simplified trigger case handling, and the output examples from the update query.

MySQL: select random individual from available to populate new table

I am trying to automate the production of a roster based on leave dates and working preferences. I have generated some data to work with and I now have two tables - one with a list of individuals and their preferences for working on particular days of the week(e.g. some prefer to work on a Tuesday, others only every other Wednesday, etc), and another with leave dates for individuals. That looks like this, where firstpref and secondpref represent weekdays with Mon = 1, Sun = 7 and firstprefclw represents a marker for which week of a 2 week pattern someone prefers (0 = no pref, 1 = wk 1 preferred, 2 = wk2 preferred)
initials | firstpref | firstprefclw | secondpref | secondprefclw
KP | 3 | 0 | 1 | 0
BD | 2 | 1 | 1 | 0
LW | 3 | 0 | 4 | 1
Then there is a table leave_entries which basically has the initials, a start date, and an end date for each leave request.
Finally, there is a pre-calculated clwdates table which contains a marker (a 1 or 2) for each day in one of its columns as to what week of the roster pattern it is.
I have run this query:
SELECT #tdate, DATE_FORMAT(#tdate,'%W') AS whatDay, GROUP_CONCAT(t1.initials separator ',') AS available
FROM people AS t1
WHERE ((t1.firstpref = (DAYOFWEEK(#tdate))-1
AND (t1.firstprefclw = 0 OR (t1.firstprefclw = (SELECT c_dates.clw from clwdates AS c_dates LIMIT i,1))))
OR (t1.secondpref = (DAYOFWEEK(#tdate))-1
AND (t1.secondprefclw = 0 OR (t1.secondprefclw = (SELECT c_dates.clw from clwdates AS c_dates LIMIT i,1)))
OR ((DAYOFWEEK(#tdate))-1 IN (0,5,6))
AND t1.initials NOT IN (SELECT initials FROM leave_entries WHERE #tdate BETWEEN leave_entries.start_date and leave_entries.end_date)
);
My output from that is a list of dates with initials of the pattern:
2018-01-03;Wednesday;KP,LW,TH
My desired output is
2018-01-03;Wednesday;KP
Where the initials of the person have been randomly selected from the list of available people generated by the first set of SELECTs.
I have seen a SO post where a suggestion of how to do this has been made involving SUBSTRING_INDEX (How to select Random Sub string,which seperated by coma(",") From a string), however I note the comment that CSV is not the way to go, and since I have a table which is not CSV, I am wondering:
How can I randomly select an individual's initials from the available ones and create a table which is basically date ; random_person?
So I figured out how to do it.
The first select (outlined above) forms the heart of a PROCEDURE called ROWPERROW() and generates a table called available_people
This is probably filthy MySQL code, but it works:
SET #tdate = 0
DROP TABLE IF EXISTS on_call;
CREATE TABLE working(tdate DATE, whatDay VARCHAR(20), selected VARCHAR(255));
DELIMITER //
DROP PROCEDURE IF EXISTS ROWPERROW2;
CREATE PROCEDURE ROWPERROW2()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE kk INT DEFAULT 0;
SET n=90; -- or however many days the roster is going to run for
SET kk=0;
WHILE kk<n DO
SET #tdate = (SELECT c_dates.fulldate from clwdates AS c_dates LIMIT kk,1);
INSERT INTO working
SELECT #tdate, DATE_FORMAT(#tdate,'%W') AS whatDay, t1.available
FROM available_people AS t1 -- this is the table created by the first query above
WHERE tdate = #tdate ORDER BY RAND() LIMIT 1;
SET kk = kk + 1;
END WHILE;
end;
//
DELIMITER ;
CALL ROWPERROW2();
SELECT * from working;

How to create a trigger on updating other table

I want to create table name birthrate that relates to the main table birth_t, so when I insert data to birth_t, automatically birthrate table will also be updated.
Birth_t fields:
Birth_id
Name
Birthplace
Birthdate
Sex
Height
Weight
Mother
Father
Birthrate fields:
Id
Year (from Birthdate field)
Sum (summing birth rate from the year, so we know how many babies that born in certain year)
How to create trigger for those?
You will need to get the year from Birthdate and check it against the records in the other table to update the applicable record. This is how you can do it:
delimiter |
CREATE TRIGGER birthrata_update BEFORE INSERT ON test1
FOR EACH ROW
BEGIN
insert into Birthrate(Year, Sum)
select New.Year, 0
from BirthRate
where not exists (select 1 from BirthRate BR where BR.Year = New.Year limit 0, 1 );
update Birthrate
set Sum = Sum + 1
where Birthrate.Year = YEAR(NEW.Birthdate);
END;
|
This trigger should insert a row to BirthRate if it did not exist with an initial value of 0. And then it will increment the Sum.

Efficient way to remove successive duplicate rows in MySQL

I have a table with columns like (PROPERTY_ID, GPSTIME, STATION_ID, PROPERTY_TYPE, VALUE) where PROPERTY_ID is primary key and STATION_ID is foreign key.
This table records state changes; each row represents property value of some station at given time. However, its data was converted from old table where each property was a column (like (STATION_ID, GPSTIME, PROPERTY1, PROPERTY2, PROPERTY3, ...)). Because usually only one property changed at time I have lots of duplicates.
I need to remove all successive rows with same values.
Example. Old table contained values like
time stn prop1 prop2
100 7 red large
101 7 red small
102 7 blue small
103 7 red small
The converted table is
(order by time,type) (order by type,time)
time stn type value time stn type value
100 7 1 red 100 7 1 red
100 7 2 large 101 7 1 red
101 7 1 red 102 7 1 blue
101 7 2 small 103 7 1 red
102 7 1 blue 100 7 2 large
102 7 2 small 101 7 2 small
103 7 1 red 102 7 2 small
103 7 2 small 103 7 2 small
should be changed to
time stn type value
100 7 1 red
100 7 2 large
101 7 2 small
102 7 1 blue
103 7 1 red
The table contains about 22 mln rows.
My current approach is to use procedure to iterate over the table and remove duplicates:
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE id INT;
DECLARE psid,nsid INT DEFAULT null;
DECLARE ptype,ntype INT DEFAULT null;
DECLARE pvalue,nvalue VARCHAR(50) DEFAULT null;
DECLARE cur CURSOR FOR
SELECT station_property_id,station_id,property_type,value
FROM station_property
ORDER BY station_id,property_type,gpstime;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO id,nsid,ntype,nvalue;
IF done THEN
LEAVE read_loop;
END IF;
IF (psid = nsid and ptype = ntype and pvalue = nvalue) THEN
delete from station_property where station_property_id=id;
END IF;
SET psid = nsid;
SET ptype = ntype;
SET pvalue = nvalue;
END LOOP;
CLOSE cur;
END
However, it is too slow. On test table with 20000 rows it removes 10000 duplicates for 6 minutes. Is there a way to optimize the procedure?
P.S. I still have my old table intact, so maybe it is better to try and convert it without the duplicates rather than dealing with duplicates after conversion.
UPDATE.
To clarify which duplicates I want to allow and which not.
If a property changes, then changes back, I want all 3 records to be saved, even though first and the last contains same station_id, type, and value.
If there are several successive (by GPSTIME) records with same station_id, type, and value, I want only the first one (which represents the change to that value) to be saved.
In short, a -> b -> b -> a -> a should be optimized to a -> b -> a.
SOLUTION
As #Kickstart suggested, I've created new table, populated with filtered data. To refer previous rows, I've used approach similar to one used in this question.
rename table station_property to station_property_old;
create table station_property like station_property_old;
set #lastsid=-1;
set #lasttype=-1;
set #lastvalue='';
INSERT INTO station_property(station_id,gpstime,property_type,value)
select newsid as station_id,gpstime,newtype as type,newvalue as value from
-- this subquery adds columns with previous values
(select station_property_id,gpstime,#lastsid as lastsid,#lastsid:=station_id as newsid,
#lasttype as lasttype,#lasttype:=property_type as newtype,
#lastvalue as lastvalue,#lastvalue:=value as newvalue
from station_property_old
order by newsid,newtype,gpstime) sub
-- we filter the data, removing unnecessary duplicates
where lastvalue != newvalue or lastsid != newsid or lasttype != newtype;
drop table station_property_old;
Possibly create a new table, populated with a select from the existing table using a GROUP BY. Something like this (not tested so excuse any typos):-
INSERT INTO station_property_new
SELECT station_property_id, station_id, property_type, value
FROM (SELECT station_property_id, station_id, property_type, value, COUNT(*) FROM station_property GROUP BY station_property_id, station_id, property_type, value) Sub1
Regarding chainging properties, cant you put a unique constraint to ensure the combination of station/type/value columns is unique. That way you will not be able to change it to a value which will result in a duplication.

mysql update between row and shift current to right

how to update column value of specific id and shift after to right.
id track
1 3
2 5
3 8
4 9
want to update id 3 track column value to 10, result like this
id track
1 3
2 5
3 10
4 8
5 9
id column is auto_increment
or any suggestion it's my pleasure.
thank you.
You should avoid tweaking auto_increments. Auto increment keys are usually supposed to be used internally (e.g. for linking purposes). If you want to order tracks, i suggest you add a seperate numeric field "ordernro" to the table and update that
To add a column order nro to a table named album, do like this:
alter table album add ordernro int(2) after id;
Then copy the current value for id into this new column:
update album set ordernro=id;
(do this only once after adding the column)
To insert track 10 at position 3 first shift the rows:
update album set ordernro = ordernro + 1 where ordernro >= 3;
And then insert track 10:
insert into album (ordernro, track) values (3, 10);
Remember to update your existing insert/update/select statements accordingly.
The result can be checked by:
select * from album order by ordernro;
(The id will now be "mixed up", but that doesn't matter)
UPDATE table SET id = id + 1 WHERE id >= x;
x being the id where you place your current track.
The problem with JK 's answer is that MySQL returns error saying that is can't UPDATE because the index at x+1 would be duplicate.
What I did is
UPDATE table SET id = id + 100 WHERE id >= x;
UPDATE table SET id = id - 99 WHERE id >= x;
And then INSERT my row at index x