Update value of row in mysql with conditions? - php

I want to achieve something like this using php and mysql
if the customer has an account with rewards and wants to spend rewards, how do i update the table so that it will going to subtract the spent reward to the table.
Definitely it will going to get the sum of reward by customer_id then subtract the spent reward. IF the first row(reward) is less than the spent value, it will going to subtract all then go to next row get the difference from previous result until the value of spent is equal to 0.
sample:
spent = 60
id_customer = 2
I have a table like this
id | id_customer | reward
1 | 2 | 50
2 | 2 | 20
3 | 3 | 100
4 | 4 | 5
the result should be something like this:
1st row: 50(value of first row) - 60 = 0 (with remaining 10)
2nd row: 20(value of 2nd row) - 10 (remaining points from first row) = 0
id | id_customer | reward
1 | 2 | 0
2 | 2 | 10
3 | 3 | 100
4 | 4 | 5
Hope that makes sense. Thanks

This is the logic of my solution (of course, maybe more than this one and a better ones):
Get the set of rows for that customer (id_customer = 2) and loop through the rows returned.
In each iteration, compare the value of field reward against the amount you like to subtract (60).
If the actual value is >= 60, update that row and exit. If not, update it with 0, update the remain value (60 - row value) and go to the next item in the iteration doing the same action.

In MySQL, I think the best way to do this is with variables. This should work:
declare #spent := 60;
update tablelikethis
set reward = (case when #spent = 0 then reward
when #spent >= reward
then (case when (#tmp := #spent) is null then NULL
when (#spent := #spent - reward) is null then NULL
else 0
end)
else (case when (#tmp := #spent) is null then NULL
when (#spent := 0) is null then NULL
else reward - #tmp
end)
end)
where id_customer = 2
order by id;
MySQL makes this a little hard to do in a single update, because you cannot use order by with a join. The variable version just has to deal with logic on whether the amount remaining for the reward is bigger or less than the amount remaining being spent.

I'd structure your database in a different way. You could create a column called "reward_points" in the customer table, and have a separate reward table. The structure is:
REWARD_TABLE
----------------------------------
reward_id | customer_id | reward
----------------------------------
1 | 2 | 50
2 | 2 | 20
3 | 3 | 100
4 | 4 | 5
CUSTOMER_TABLE
-------------------------------------------------
customer_id | name | reward_points
-------------------------------------------------
1 | Eddard Stark | 0
2 | Jaime Lannister | 70
3 | Joffrey Baratheon | 100
4 | Theon Greyjoy | 5
Then you could just update the CUSTOMER_TABLE with the new value. You could keep the REWARD_TABLE as a 'reward history'. Even better... upon purchase, you could add a negative transaction to the REWARD_TABLE, so when you would do a SELECT SUM(reward) asRewardFROM reward_table WHERE customer_id = 2 GROUP BY customer_id, it would count all the negative transactions as well, resulting in something, which is close to your concept.

Related

Getting only one result for a "football matchup" per team per week

I'm putting together a new project, and one of the things I need to do is get the results of a Fake Football (American) match. I'm doing this in php and mysql, utilizing CodeIgniter as my framework. My dbfiddle is as follows:
https://www.db-fiddle.com/f/5Q7QezddpNEGabaia2w5FQ/0
Now, as you can see, each team has an entry for home_team_id and away_team_id. What I would like to do is have a query that gets only ONE result for each team (regardless if they are home or away). I'd rather not programmatically process this data if I don't have to.
The results should be something along the lines of the following:
SELECT week, home_team_id, away_team_id,
my_score, their_score,
a.team_name as home_team, b.team_name as away_team
FROM nfl_user_matchups nm
LEFT JOIN user_teams a ON nm.home_team_id = a.user_teams_id
LEFT JOIN user_teams b ON nm.away_team_id = b.user_teams_id
WHERE week = 1
Expected Final Data would be something like this (my_score would be home_team_id score, their_score would be away_team_id score):
+------+--------------+--------------+----------+-------------+
| week | home_team_id | away_team_id | my_score | their_score |
+------+--------------+--------------+----------+-------------+
| 1 | 3 | 9 | 112 | 144 |
+------+--------------+--------------+----------+-------------+
| 1 | 7 | 2 | 85 | 96 |
+------+--------------+--------------+----------+-------------+
| 1 | 1 | 6 | 111 | 114 |
+------+--------------+--------------+----------+-------------+
| 1 | 4 | 5 | 99 | 125 |
+------+--------------+--------------+----------+-------------+
| 1 | 8 | 10 | 140 | 122 |
+------+--------------+--------------+----------+-------------+
Your problem statement basically means that a pair of teams competing, viz., (1,2) are to be treated same as (2,1). One way to handle such requirements is to ensure that for any match between these two teams, we ensure that they are in the same order. So, basically we get the Least() team id value out of the two teams, and always put it in the first index; and the Greatest() value always at the second (last) index. It is noteworthy that Greatest() is not same as Max(). Max() function computes maximum on a column; while Greatest() is generally used to compare values across a row.
Now, we can simply GROUP BY on this pair and compute the aggregates as desired. While determining home/away scores, you will need to use CASE .. WHEN expression to determine whether a particular row has home id the least, or away id:
SELECT
week,
LEAST(home_team_id, away_team_id) AS home_id,
GREATEST(home_team_id, away_team_id) AS away_id,
MAX(CASE
WHEN LEAST(home_team_id, away_team_id) = home_team_id
THEN my_score
ELSE their_score
END) AS home_score,
MAX(CASE
WHEN GREATEST(home_team_id, away_team_id) = away_team_id
THEN their_score
ELSE my_score
END) AS away_score
FROM nfl_user_matchups
WHERE week = 1
GROUP BY
week,
home_id,
away_id;
View on DB Fiddle

Updating the table with new value by finding specific row

I have a table that I add information depending on the order number.
So when I enter information, I add some column names as numbers.
Then update the rows with new values.
My table takes 3 values everytime I insert value.
order number| total left | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9|
------------------------------------------------------------------------
11 | 100 | a | b | c | d | e | f | 0 | | |
------------------------------------------------------------------------
12 | 10 | x | y | z | 0 | | | s | d | f|
-------------------------------------------------------------------------
When I try to add new column, the value of the new rows in every other value becomes null or 0 depending on if it is int or varchar.
When I insert 3 values to order number 12, I want the last 0 in that row to be updated.
(In this case, 4-5-6 but I get 7-8-9 updated.)
So what is the best way for finding the last row which is 0
(in this case column 4 for order number 12 and insert the new values of s,d,f to the 4-5-6 instead of 7-8-9 ?
So maybe something like:
Loop through rows, find 0, insert 3 rows, break.
I take the last column:
$NewColumnNameKoliAdet=$LastColumnName+1;
$NewColumnNameMusteri=$LastColumnName+2;
$NewColumnNameTarih=$LastColumnName+3;
Then I add columns and update the table.
$Query="ALTER TABLE `koli_stok_hareketleri`
ADD `$NewColumnNameKoliAdet` INT(11) NOT NULL AFTER `$LastColumnName`,
ADD `$NewColumnNameMusteri` VARCHAR(100) NOT NULL AFTER `$NewColumnNameKoliAdet`,
ADD `$NewColumnNameTarih` VARCHAR(100) NOT NULL AFTER `$NewColumnNameMusteri`;";
$Query="UPDATE koli_stok_hareketleri SET kalan_koli=kalan_koli-
'$Uretilen_Koli',
`$NewColumnNameKoliAdet` = '$Uretilen_Koli',
`$NewColumnNameMusteri` = '$Musteri_ismifromrow',
`$NewColumnNameTarih` = '$Now'
WHERE koli_ismi ='$Koli_IsmifromRow' AND
koli_parti_no='$Parti_NofromRow'";
So the problem is it adds three value to each row automatically and but when I update, I need to update the order number 12 from 4th column not 7.

PHP / MySQL: recursive array / recursive SELECT

EXPLAIN
Let's say we have this transaction table :
+----+-------------+--------+----------------+----------------+---------------------+
| id | id_customer | amount | id_where_trans | id_money_from | date_trans |
+----+-------------+--------+----------------+----------------+---------------------+
| 1 | 10 | 10 | 100 | NULL | 2015-07-20 10:20:30 |
| 2 | 10 | -2 | 100 | NULL | 2015-07-21 09:10:11 |
| 3 | 10 | 7 | 120 | NULL | 2015-07-24 18:22:25 |
| 4 | 10 | -11 | 120 | here the magic | 2015-07-24 18:22:26 |
+----+-------------+--------+----------------+----------------+---------------------+
Read this in "human" language:
id 1 => Customer Alessandro (id_customer 10) charge 10€ on his account in shop A (id_where trans = 100)
id 2 => Customer Alessandro spent 2€ on Shop A
id 3 => Customer Alessandro charge 7€ on his account in shop B
id 4 => Customer ALessandro spend 11€ in shop B.
At the end of period (month, for example), Shop B need to receive 8€ (+10-2) from another shop, in our example shop A.
/end of human read.
You imagine that insert is a simple (for id 4, for example):
INSERT INTO transaction (id_customer, amount, id_where_trans, date) VALUES (10,-11,120,2015-07-24 18:22:26)
GOAL
My goal is set - during the insert, and if possible / simpler via PHP - the SQL splitted in two or more SELECT:
INSERT INTO transaction (id_customer, amount, id_where_trans, id_money_from, date) VALUES (10,-8,120,100,2015-07-24 18:22:26)
INSERT INTO transaction (id_customer, amount, id_where_trans, id_money_from, date) VALUES (10,-3,120,NULL,2015-07-24 18:22:27)
+----+-------------+--------+----------------+------------+---------------------+
| id | id_customer | amount | id_where_trans | id_money_from | date |
+----+-------------+--------+----------------+------------+---------------------+
| 1 | 10 | 10 | 100 | NULL | 2015-07-20 10:20:30 |
| 2 | 10 | -2 | 100 | NULL | 2015-07-21 09:10:11 |
| 3 | 10 | 7 | 120 | NULL | 2015-07-24 18:22:25 |
| 4 | 10 | -8 | 120 | 100 | 2015-07-24 18:22:26 |
| 5 | 10 | -3 | 120 | NULL | 2015-07-24 18:22:27 |
+----+-------------+--------+----------------+------------+---------------------+
If I can get a table with that informations, I can run a query that make my final job correctly.
Basically, I need to calculate the id_shop where money are taken for discharge (in this case, -8 from 100, that made previous charge, and so is NOT NULL, and -3 from 120,itself, THIS IS NULL).
Please note that FIRST I consume / discharge the previous charge (id 4 now has id_money_from 100), AFTER I will consume / discharge others amounts (id 5 in effect is NULL, because that -3 has taken from id 3)
ASSUMPTION / MANDATARY
1) id are INCREMENTAL, no concurrency. Date are INCREMENTAL, date of id 4 is >= of id 3 and so on.
2) If amount of last recharge is made from same id where transaction is done (see id 1 and id 2) insert NULL (I need mandatary NULL)
3) First charge made, first need to be zero-ed, and so on.
MY LOGIC / PSEUDOCODE
1) If a transaction is negative, make a recursive getting LAST positive charge which, summed to the negative susequential, is not zero.
getted this charge, if id_where_trans==id_money_from we need insert, simply insert, with NULL
INSERT INTO transaction (id_customer, amount, id_where_trans, id_money_from, date) VALUES (10,-2,120,NULL,2015-07-24 18:22:26)
Recursive start here
If this amount is <= of last recharge, walking in database and split negative in two or more id_where_trans (problaby in real scenario this will be impossible, but I need to think that amount from discharge (id_money_from) could be splitted by 2, 3, x id_where_trans). For example, if SHOP A charge +1, Shop B charge +1, Shop C charge +1 and SHOP D DISCHARGE -3, we need to insert 3 different rows.
$amount_to_discharge = x;
$last_positive = $query->("SELECT * FROM transaction WHERE "); // make the SUB-SUM
if ($last_positive['amount'] >= $amount_to_discharge) {
$query->("INSERT INTO......");
} else {
// start recursive
$sql = "SELECT * FROM AMOUNT WHERE amount > 0 AND id < $last_positive['id']";
$new_search = $query->sql($sql);
// how implement correctly that recursive?
}
Thank you guy. Let me know if you need others explain!

Column Calculator

I have the following table and want to know how to set up a column total to calculate the sum of the row. I want the total column to calculate first_bid - second_bid.
id | First Bid | Second Bid | Total
0 | 7 | 1 | (first_bid)-(second_bid)
1 | 8 | 2 |
2 | 5 | 3 |
3 | 4 | 4 |
4 | 5 | 5 |
5 | 5 | 6 |
I need to display to the user all previous bids and total on a page. The total should be in descending order also.
SELECT id, First_Bid, Second_Bid, First_Bid - Second_Bid AS Total
For the grand total, you'd have to run a second query with SUM() aggregate functions. Which is somewhat redundant, since you can just do the summation in your client as you retrieve the data. e.g.
$total = 0;
while($row = fetch_from_db($result)) {
$total += $result['Total'];
... display row data ...
}
... display total ...
You can just calculate the total when you are querying the database.
SELECT first_bid, second_bid, (first_bid - second_bid) as total FROM table ORDER BY 3 DESC
Something along these lines
Try this query:
SELECT *, (First Bid-Second Bid) as total from TABLE

mysql speed of query - selecting max value of every 3 rows

I have a table that holds price information. I need to select the max value of every three rows. EXAMPLE:
Table `daily_high`
____ _______
| ID | HIGH |
| 1 | 24.65 |
| 2 | 24.93 |
| 3 | 26.02 |
| 4 | 25.33 |
| 5 | 25.16 |
| 6 | 25.91 |
| 7 | 26.05 |
| 8 | 28.13 |
| 9 | 27.07 |
|____|_______|
Desired output to new table (ID will be auto-increment so don't assume an association exists between this ID 1 and the daily_high ID 1:
____ ___________
| ID | 3MaxHIGH |
|____|___________|
| 1 | 26.02 |
| 2 | 25.91 |
| 3 | 28.13 |
|____|___________|
I want to compare IDs 1,2, and 3 to determine the high value among them. Then once I have compared 1-3, I want to move on to 4 through 6, then 7 through 9, etc until I've done this for all values contained in the table (currently about 400,000 values). I have written code that uses
SELECT max(HIGH) FROM daily_high as dh1 JOIN (SELECT max(HIGH) FROM daily_high WHERE id >= dh1 AND id < (dh1.id + 3))
This works but is horribly slow. I've tried using the SELECT statement where I identify the column values to be pull for display, meaning between the SELECT and FROM parts of the query.
I've tried to use JOIN to join all 3 rows onto the same table for comparison but it too is horribly slow. By slow I mean just under 10 seconds to gather information for 20 rows. This means that the query has analyzed 60 rows (20 groups of 3) in 9.65879893303 seconds (I didn't make this up, I used microtime() to calculate it.
Anyone have any suggestions for faster code than what I've got?
Keep in mind that my actual table is not the same as what I've posted above, but it the concept is the same.
Thanks for any help.
If you ID it continous you can make this
SELECT floor(id/3) as range, max(HIGH) FROM daily_high GROUP BY range;
Why not to use DIV operator for grouping your aggregation:
SELECT (id-1) DIV 3 + 1 AS ID, MAX(high) AS 3MaxHIGH
FROM daily_high
GROUP BY (id-1) DIV 3
This query gives the same result.
ID 3MaxHIGH
1 26.02
2 25.91
3 28.13
I was unable to run your query, and I believe that this one is faster.
UPD: To ensure that you have valid groups for your ranges, use this query:
select id, high, (id-1) div 3 + 1 from daily_high
result:
id high (id-1) div 3 + 1
1 24.65 1
2 24.93 1
3 26.02 1
4 25.33 2
5 25.16 2
6 25.91 2
7 26.05 3
8 28.13 3
9 27.07 3
Fuller answer with an example. The following code will do what I think you want.
SELECT FLOOR((row - 1) / 3), MAX(Sub1.high)
FROM (SELECT #row := #row + 1 as row, daily_high.*
FROM daily_high, (SELECT #row := 0) r) Sub1
GROUP BY FLOOR((row - 1) / 3)
ORDER BY Sub1.ID
The below query worked for me on a test table. perhaps not the best, but the other solutions failed on my test table.
This does require the ID's to be sequential. Also be sure to put an index on High aswell for speed.
SELECT FLOOR(T1.Id/3)+1 AS Id, ROUND(GREATEST(T1.High, T2.High, T3.High),2) AS High FROM `daily_high` T1, `daily_high` T2, `daily_high` T3
WHERE T2.Id=T1.Id+1
AND T3.Id=T2.Id+1
AND MOD(T1.Id, 3)=1
logic: if(id is divisible by 3, id/3-1, id/3)
select if(mod(id,3) = 0,floor(id/3)-1,floor(id/3)) as group_by_col , max(HIGH)
FROM daily_high GROUP BY group_by_col;

Categories