Finding min and max value of the table in a constant time - mysql

I have a table which contains relative large data,
so that it takes too long for the statements below:
SELECT MIN(column) FROM table WHERE ...
SELECT MAX(column) FROM table WHERE ...
I tried index the column, but the performance still does not suffice my need.
I also thought of caching min and max value in another table by using trigger or event.
But my MySQL version is 5.0.51a which requires SUPER privilege for trigger and does not support event.
It is IMPOSSIBLE for me to have SUPER privilege or to upgrade MySQL.
(If possible, then no need to ask!)
How to solve this problem just inside MySQL?
That is, without the help of OS.

If your column is indexed, you should find min(column) near instantly, because that is the first value MySQL will find.
Same goes for max(column) on an indexed column.
If you cannot add an index for some reason the following triggers will cache the MIN and MAX value in a separate table.
Note that TRUE = 1 and FALSE = 0.
DELIMITER $$
CREATE TRIGGER ai_table1_each AFTER INSERT ON table1 FOR EACH ROW
BEGIN
UPDATE db_info i
SET i.minimum = LEAST(i.minimum, NEW.col)
,i.maximum = GREATEST(i.maximum, NEW.col)
,i.min_count = (i.min_count * (new.col < i.minumum))
+ (i.minimum = new.col) + (i.minimum < new.col)
,i.max_count = (i.max_count * (new.col > i.maximum))
+ (i.maximum = new.col) + (new.col > i.maximum)
WHERE i.tablename = 'table1';
END $$
CREATE TRIGGER ad_table1_each AFTER DELETE ON table1 FOR EACH ROW
BEGIN
DECLARE new_min_count INTEGER;
DECLARE new_max_count INTEGER;
UPDATE db_info i
SET i.min_count = i.min_count - (i.minimum = old.col)
,i.max_count = i.max_count - (i.maximum = old.col)
WHERE i.tablename = 'table1';
SELECT i.min_count INTO new_min_count, i.max_count INTO new_max_count
FROM db_info i
WHERE i.tablename = 'table1';
IF new_max_count = 0 THEN
UPDATE db_info i
CROSS JOIN (SELECT MAX(col) as new_max FROM table1) m
SET i.max_count = 1
,i.maximum = m.new_max;
END IF;
IF new_min_count = 0 THEN
UPDATE db_info i
CROSS JOIN (SELECT MIN(col) as new_min FROM table1) m
SET i.min_count = 1
,i.minimum = m.new_min;
END IF;
END $$
DELIMITER ;
The after update trigger will be some mix of the insert and delete triggers.

Related

MySQL - Update Column Value with Function and Trigger Before Insert

i'm trying to update 2 column with trigger before insert, but i have unexpected result. i insert some data and the 2 last column will automatically inserted with values, here my first attempt
see? the last 2 column is null even i set some trigger and function to fill that columns automatically. Here my second attempt WITH EXACTLY SAME DATA
the last 2 column is filled with data, but i don't understand why the first attempt is fail?
here my trigger i use in the column total_harga
CREATE TRIGGER `set_total_harga` BEFORE INSERT ON `tbl_transaksi_detail`
FOR EACH ROW BEGIN
set NEW.total_harga = hitungTotalHargaPerItem(NEW.qty, NEW.harga_satuan);
END
trigger for column harga_satuan
CREATE TRIGGER `set_harga_satuan` BEFORE INSERT ON `tbl_transaksi_detail`
FOR EACH ROW BEGIN
set NEW.harga_satuan = set_Harga_Unit(NEW.unit, NEW.id_barang, NEW.no_transaksi);
END
function set_Harga_Unit
BEGIN
DECLARE
q,
id_toko INT;
SET
id_toko =(
SELECT DISTINCT
`tbl_transaksi`.`id_toko`
FROM
`tbl_transaksi`,
`tbl_transaksi_detail`
WHERE
`tbl_transaksi`.`no_transaksi` = no_trans
); IF unit = "PCS" THEN
SET
q =(
SELECT
`tbl_harga_jual`.`harga_pcs`
FROM
`tbl_harga_jual`
WHERE
`tbl_harga_jual`.`id_barang` = id_brg AND `tbl_harga_jual`.`id_toko` = id_toko
); RETURN q; ELSEIF unit = "PAK" THEN
SET
q =(
SELECT
`tbl_harga_jual`.`harga_pak`
FROM
`tbl_harga_jual`
WHERE
`tbl_harga_jual`.`id_barang` = id_brg AND `tbl_harga_jual`.`id_toko` = id_toko
); RETURN q; ELSEIF unit = "KARTON" THEN
SET
q =(
SELECT
`tbl_harga_jual`.`harga_karton`
FROM
`tbl_harga_jual`
WHERE
`tbl_harga_jual`.`id_barang` = id_brg AND `tbl_harga_jual`.`id_toko` = id_toko
); RETURN q;
END IF; RETURN q;
END
function hitungTotalHargaPerItem
BEGIN
DECLARE hasil int;
set hasil = qty * harga_satuan;
RETURN hasil;
END
The root cause serms to be the select that sets id_toko variable's value:
SET
id_toko =(
SELECT DISTINCT
`tbl_transaksi`.`id_toko`
FROM
`tbl_transaksi`,
`tbl_transaksi_detail`
WHERE
`tbl_transaksi`.`no_transaksi` = no_trans
);
In the select you inner join tbl_transaksi_detail (the table with the trigger in question) on another table. However, in the 1st case tbl_transaksi_detail is still empty (the trigger is before insert), therefore id_toko variable is set to null.
This will result q being null, which in turn results in the entire calculation set to null.
In the 2nd case there is already a record inserted into tbl_transaksi_detail table, therefore the calculation returns a non null value. But it returns the correct values only because the 1st and 2nd records' details are exactly the same.
I do not really understand that select that calculates id_toko anyway. If that is a transaction id, then you may use last_insert_id() if it is auto increment and the transaction record has just been created or max(id_toko) to get the highest value of id_toko (this is not multi user safe).
it seem i have mistaken select query in function set_Harga_Unit, based on clues from #Shadow
SET
id_toko =(
SELECT DISTINCT
`tbl_transaksi`.`id_toko`
FROM
`tbl_transaksi`,
`tbl_transaksi_detail`<<== I DON'T NEED THIS
WHERE
`tbl_transaksi`.`no_transaksi` = no_trans
); IF unit = "PCS" THEN
when first insert in tbl_transaksi_detail, the value no_transaksi is null because i use trigger before insert in empty table (tbl_transaksi_detail), so i remove tbl_transaksi_detail from query
SET
id_toko =(
SELECT DISTINCT
`tbl_transaksi`.`id_toko`
FROM
`tbl_transaksi`
WHERE
`tbl_transaksi`.`no_transaksi` = no_trans
); IF unit = "PCS" THEN
now it working, thanks everybody!

MySQL 1422, explicit or implicit commit is not allowed in trigger

I understand that I cannot do a transaction inside a trigger, but I CAN inside a procedure. And I should be able to call a procedure from a trigger. Which is exactly what I'm doing.
TABLE A has an "after update trigger".
I only want to call the procedure if one of two columns has been changed.
TABLE A TRIGGER:
IF (
NEW.colA != OLD.colA
OR
NEW.colB != OLD.colB
) THEN
call setBonuses( NEW.colA, NEW.colB );
END IF
The setBonuses SP effects TABLE B by doing some calculations using TABLE_A.colA,TABLE_A.colB (I don't think it's relevant, but TABLE B does have an "after update trigger", but it has a conditional to only do its update if fields NOT effected by the below procedure are changed, so it does 'nothing' when the bonus field is updated.)
THE STORED PROCEDURE:
begin
IF A > B THEN
SET n = A;
...
ELSEIF A < B THEN
SET n = B;
...
END IF;
start transaction;
-- Bonuses
UPDATE TABLE_B
SET bonus = 0
WHERE... ;
UPDATE TABLE_B
SET bonus = bonus + n
WHERE...;
UPDATE TABLE_B
SET bonus = bonus + n
WHERE...;
UPDATE TABLE_B
SET bonus = bonus + n
WHERE...;
UPDATE TABLE_B
SET bonus = bonus + n
WHERE...;
UPDATE TABLE_B
SET bonus = bonus + n
WHERE...;
commit;
end
The SP works fine if called directly by the application, however, I don't want to have to explicitly call it as a chain in some event, I really just need it to do its calcs and update TABLE B - whenever someone changed TABLE A (colA or colB).
Any reason why this isn't possible.

how to optimise MySql function to work for concurrent users

I am new to MySQL. Please can you advice on how can i modify below function to ensure it does not throw locking errors when called by multiple users at the same time.
CREATE FUNCTION `get_val`(`P_TABLE` VARCHAR(50)) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE pk_value INT DEFAULT 0;
DECLARE pk_found INT DEFAULT 0;
SELECT 1 INTO pk_found FROM pk_keys WHERE TABLE_NAME = P_TABLE;
IF pk_found = 1
THEN
UPDATE pk_keys SET TABLE_VALUE = (TABLE_VALUE + 1 ) WHERE TABLE_NAME = P_TABLE;
ELSE
INSERT INTO pk_keys VALUES ( P_TABLE, 1 );
END IF;
SELECT TABLE_VALUE INTO pk_value FROM pk_keys WHERE TABLE_NAME = P_TABLE;
RETURN pk_value;
END
thanks
CREATE FUNCTION `get_val`(`P_TABLE` VARCHAR(50)) RETURNS int(11)
DETERMINISTIC
MODIFIES SQL DATA
BEGIN
DECLARE pk_value INT DEFAULT 0;
IF EXISTS (SELECT 1 FROM pk_keys WHERE TABLE_NAME = P_TABLE)
THEN
SELECT TABLE_VALUE + 1 INTO pk_value FROM pk_keys WHERE TABLE_NAME = P_TABLE FOR UPDATE;
UPDATE pk_keys SET TABLE_VALUE = pk_value WHERE TABLE_NAME = P_TABLE;
ELSE
SET pk_value = 1;
INSERT INTO pk_keys VALUES ( P_TABLE, pk_value );
END IF;
RETURN pk_value;
END
Have a look at SELECT ... FOR UPDATE and SELECT ... LOCK IN SHARE MODE Locking Reads
Let us look at another example: We have an integer counter field in a
table child_codes that we use to assign a unique identifier to each
child added to table child. It is not a good idea to use either
consistent read or a shared mode read to read the present value of the
counter because two users of the database may then see the same value
for the counter, and a duplicate-key error occurs if two users attempt
to add children with the same identifier to the table.
Here, LOCK IN SHARE MODE is not a good solution because if two users
read the counter at the same time, at least one of them ends up in
deadlock when it attempts to update the counter.
To implement reading and incrementing the counter, first perform a
locking read of the counter using FOR UPDATE, and then increment the
counter. For example:
SELECT counter_field FROM child_codes FOR UPDATE;
UPDATE child_codes SET counter_field = counter_field + 1;
A SELECT ... FOR UPDATE reads the latest available data, setting
exclusive locks on each row it reads. Thus, it sets the same locks a
searched SQL UPDATE would set on the rows.
Also I replaced your if condition. EXISTS stops as soon as a row is found.

MySql Error 1054 when inserting into table that has trigger

I have created a trigger on a table, and when I try to insert data into it I get MySql error "Error Code: 1054 'unknown column license_key in field list'"
The INSERT I try to do is this:
INSERT INTO LOAD_MASTER(license_key, state, total_pageviews, total_visitors, max_visitors, max_pageviews, ip, secret, read_time, url)
VALUES ("order55555hytgtrfderfredfredfredftyu8ikloi98nhygt6", "preparing", 400, 1000, 200, 400, "202,2,35,36", "Hemmeligheden", 120, "http://google.dk");
The Trigger I have created is supposed to check the TABLE LOAD_STATS for the presence of the IP entered in the LOAD_MASTER table, and then based on the results change a value in another table called LICENSE
My trigger is here:
DELIMITER //
CREATE TRIGGER ip_check AFTER INSERT ON LOAD_MASTER FOR EACH ROW
BEGIN
DECLARE MK varchar(50);
DECLARE MIP varchar(15);
DECLARE LID int(6);
SET MK = license_key;
SET MIP = ip;
SET LID = (
SELECT l.license_id
FROM license_keys k, license l
WHERE l.license_id = k.license_id
AND k.license_key = MK
);
IF (SELECT COUNT(DISTICT(master_ip)) FROM LOAD_STATS WHERE master_ip = MIP AND master_key = MK ) > 3 THEN
UPDATE LICENSE
SET STATE = 0
WHERE license_id = LID;
END IF;
END
//
DELIMITER ;
Any help on why I get this error would be much appriciated.
-Dan
In these lines
SET MK = license_key;
SET MIP = ip;
you probably meant to address NEW.license_key and NEW.ip respectively.
IMHO you can make more succinct. Try this
DELIMITER //
CREATE TRIGGER ip_check
AFTER INSERT ON load_master
FOR EACH ROW
BEGIN
IF (SELECT COUNT(DISTICT(master_ip))
FROM load_stats
WHERE master_ip = NEW.ip
AND master_key = NEW.license_key ) > 3 THEN
UPDATE license
SET state = 0
WHERE license_id =
(
SELECT l.license_id
FROM license_keys k JOIN license l
ON l.license_id = k.license_id
AND k.license_key = NEW.license_key
); -- make sure that this subquery returns only ONE record
END IF;
END //
DELIMITER ;
There is some room for improvement rewriting an UPDATE with JOIN instead of using a subquery

stored procedure syntax in mysql

I am new to writing stored Procedures and I can't seem to find the error in this procedure.
The error is marked near the where part.
I tried looking for an example where the set is done based on a if condition but I can't seem to find such an example. Can anyone point me to my error?
DELIMITER $$
CREATE PROCEDURE `incubation`.`bt_voice_modification`
(in input_slot varchar(45),in input_port varchar(45))
BEGIN
SET #SVLAN_STH:=1000;
SET #SVLAN_DTH:=999;
SET #CVLAN_DTH:=1000;
SET #FLOW_INSTANCE:=1;
UPDATE one_2_one_table
SET L2S_USER_FLOW_INSTANCE = #FLOW_INSTANCE := #FLOW_INSTANCE+1;
SET L2S_NW_SLOT = input_slot;
SET L2S_NW_PORT = input_port;
IF STH_DTH = 'STH' then
set L2S_NW_SVLAN = #SVLAN_STH :=#SVLAN_STH + 1;
ELSE
set L2S_NW_SVLAN = #SVLAN_DTH ;
set L2S_NW_CVLAN = #CVLAN_DTH :=#CVLAN_DTH + 1;
END if;
WHERE IPDSLAM_USER_SLOT = 2 AND L2S_USER_TYPE like "%gplt%";
END
Your code suggest you don't have a very clear picture of how UPDATE statement works or the exact syntax. When you put a ;, it marks the end of the (UPDATE) statement. The syntax is - for one table:
UPDATE tableX
SET columnA = what_value_should_columnA-get ,
columnB = what_value_should_columnB_get ,
...
columnX = what_value_should_columnX_get
WHERE (conditions that restrict the rows that will be affected)
ORDER BY SomeColumn ; --- this can be used in MySQL only. Standard SQL
--- (and most DBMS) do not allow ORDER BY clause in
--- UPDATE statements. Since you are using variables
--- and the order of updating affects the updated values,
--- it's essential that you include an ordering.
So, your UPDATE would be something like:
UPDATE one_2_one_table
SET L2S_USER_FLOW_INSTANCE = #FLOW_INSTANCE := #FLOW_INSTANCE+1 ,
L2S_NW_SLOT = input_slot,
L2S_NW_PORT = input_port,
L2S_NW_SVLAN = CASE WHEN STH_DTH = 'STH'
THEN #SVLAN_STH := #SVLAN_STH + 1
ELSE #SVLAN_DTH
END ,
L2S_NW_CVLAN = CASE WHEN STH_DTH = 'STH'
THEN L2S_NW_CVLAN
ELSE #CVLAN_DTH := #CVLAN_DTH + 1
END
WHERE IPDSLAM_USER_SLOT = 2
AND L2S_USER_TYPE like '%gplt%'
ORDER BY SomeColumn ;