In credits table I have
(id, user_id, process, amount, date_add, date_exp, date_redeemed, remark)
SELECT * FROM credits WHERE user_id = 2;
+----+---------+---------+--------+------------+------------+---------------+----------+
| id | user_id | process | amount | date_add | date_exp | date_redeemed | remark |
+----+---------+---------+--------+------------+------------+---------------+----------+
| 22 | 2 | Add | 200.00 | 2018-01-01 | 2019-01-01 | | Credit1 |
| 23 | 2 | Add | 200.00 | 2018-03-31 | 2019-03-31 | | Credit2 |
| 24 | 2 | Deduct | 200.00 | | | 2018-04-28 | Redeemed |
| 25 | 2 | Add | 200.00 | 2018-07-11 | 2018-10-11 | | Campaign |
| 26 | 2 | Deduct | 50.00 | | | 2018-08-30 | Redeemed |
| 27 | 2 | Add | 200.00 | 2018-10-01 | 2019-09-30 | | Credit3 |
| 28 | 2 | Deduct | 198.55 | | | 2018-10-20 | Redeemed |
+----+---------+---------+--------+------------+------------+---------------+----------+
The following query I wrote will only calculate the balance, but I don't know whether the credit is expired and used before expired.
SELECT
u.id,
email,
CONCAT(first_name, ' ', last_name) AS name,
type,
(CASE
WHEN (SUM(amount) IS NULL) THEN 0.00
ELSE CASE
WHEN
(SUM(CASE
WHEN process = 'Add' THEN amount
END) - SUM(CASE
WHEN process = 'Deduct' THEN amount
END)) IS NULL
THEN
SUM(CASE
WHEN process = 'Add' THEN amount
END)
ELSE SUM(CASE
WHEN process = 'Add' THEN amount
END) - SUM(CASE
WHEN process = 'Deduct' THEN amount
END)
END
END) AS balance
FROM
users u
LEFT JOIN
credits c ON u.id = c.user_id
GROUP BY u.id;
Or I am doing it in the wrong way? Maybe I should have done the calculation in my backend instead of SQL?
EDIT 1:
I want to calculate the balance of every user's e-wallet, but the credit will expire,
IF it was expired AND not redeemed then exclude from the balance
ELSE IF used before expired AND redeem amount < expire amount
THEN (balance - (expire amount - redeem amount))
ELSE IF used before expired AND redeem amount > expire amount
THEN the usable balance will be deducted as expire amount is not enough to deduct redeemed amount
EDIT 2:
The query above will output 351.45, my expected output is 201.45. Which will not calculate the redemption on 2018-08-30 as the redeem amount is lower than the expired amount
EDIT 3:
User table:
+----+------------+-----------+----------+----------------+----------+
| id | first_name | last_name | type | email | password |
+----+------------+-----------+----------+----------------+----------+
| 2 | Test | Oyster | Employee | test#gmail.com | NULL |
+----+------------+-----------+----------+----------------+----------+
My output:
+----+----------------+-------------+----------+---------+
| id | email | name | type | balance |
+----+----------------+-------------+----------+---------+
| 2 | test#gmail.com | Test Oyster | Employee | 351.45 |
+----+----------------+-------------+----------+---------+
Expected output:
total (200+200+200) 600
redeemed amount 448.55 (200+50+198.55)
Remaining balance is 151.45
+----+----------------+-------------+----------+---------+
| id | email | name | type | balance |
+----+----------------+-------------+----------+---------+
| 2 | test#gmail.com | Test Oyster | Employee | 151.45 |
+----+----------------+-------------+----------+---------+
There are basic structural problems with your current table. So I would propose some alterations to the table structure and subsequently application code. Table structures for Wallet systems can be very detailed; but I would suggest minimum possible changes here. I am not suggesting that it would be ideal way; but it should work. Initially, I will layout some of the problems with the current approach.
Problems:
What if there are multiple Credits available which are not yet expired ?
Out of these available Credits, some may actually have been utilized already, but not yet expired. How do we ignore them for available balance ?
Also, some may have been partially utilized. How do we account for partial utilization ?
There may be a scenario where a redemption amount spans across multiple unexpired credits. Some may get partially utilized; while some may get fully utilized.
General Practice:
We generally follow FIFO (First In First Out) approach, to give maximum benefit to the customer. So the older credits (which has higher chance of getting expired without utilization) gets utilized first.
In order to follow FIFO, we will have to effectively use a Looping technique in the query/application code every-time, in order to compute basic things, such as, "Available Wallet Balance", "Expired and Underutilized Credit", etc. Writing a query for this will be cumbersome and possibly inefficient at bigger scales
Solution:
We can add one more column amount_redeemed in your current table. It basically represent the amount which has already been redeemed against a specific credit.
ALTER TABLE credits ADD COLUMN amount_redeemed DECIMAL (8,2);
So, a filled table would look something like below:
+----+---------+---------+--------+-----------------+------------+---------------+---------------+----------+
| id | user_id | process | amount | amount_redeemed | date_add | date_exp | date_redeemed | remark |
+----+---------+---------+--------+-----------------+------------+---------------+---------------+----------+
| 22 | 2 | Add | 200.00 | 200.00 | 2018-01-01 | 2019-01-01 | | Credit1 |
| 23 | 2 | Add | 200.00 | 200.00 | 2018-03-31 | 2019-03-31 | | Credit2 |
| 24 | 2 | Deduct | 200.00 | | | | 2018-04-28 | Redeemed |
| 25 | 2 | Add | 200.00 | 0.00 | 2018-07-11 | 2018-10-11 | | Campaign |
| 26 | 2 | Deduct | 50.00 | | | | 2018-08-30 | Redeemed |
| 27 | 2 | Add | 200.00 | 48.55 | 2018-10-01 | 2019-09-30 | | Credit3 |
| 28 | 2 | Deduct | 198.55 | | | | 2018-10-20 | Redeemed |
+----+---------+---------+--------+-----------------+------------+---------------+---------------+----------+
Notice that the amount_redeemed against Credit of id = 25 is 0.00, using FIFO approach. It got a chance for redemption on 2018-10-20, but by that time, it has expired already (date_exp = 2018-10-11)
So, now once we have this setup, you can do the following things in your application code:
Populate amount_redeemed value in existing rows in the table:
This will be a one time activity. For this, formulating a single query would be difficult (that is why we are here in the first place). So I would suggest you to do it one time in your application code (eg: PHP), using Loops and FIFO approach. Look at Point 3 below, to get an idea of how to do it in application code.
Get Current Available Balance:
Query for this becomes trivial now, as we just need to calculate Sum of amount - amount_redeemed for all Add process, which are not yet expired.
SELECT SUM(amount - amount_redeemed) AS total_available_credit
FROM credits
WHERE process = 'Add' AND
date_exp > CURDATE() AND
user_id = 2
Update amount_redeemed at the time of redemption:
In this, you can firstly get all available Credits, which has amount available for redemption, and not yet expired.
SELECT id, (amount - amount_redeemed) AS available_credit
FROM credits
WHERE process = 'Add' AND
date_exp > CURDATE() AND
user_id = 2 AND
amount - amount_redeemed > 0
ORDER BY id
Now, we can loop over the above query results, and utilize the amount accordingly
// PHP code example
// amount to redeem
$amount_to_redeem = 100;
// Map storing amount_redeemed against id
$amount_redeemed_map = array();
foreach ($rows as $row) {
// Calculate the amount that can be used against a specific credit
// It will be the minimum of available credit and amount left to redeem
$amount_redeemed = min($row['available_credit'], $amount_to_redeem);
// Populate the map
$amount_redeemed_map[$row['id']] = $amount_redeemed;
// Adjust the amount_to_redeem
$amount_to_redeem -= $amount_redeemed;
// If no more amount_to_redeem, we can finish the loop
if ($amount_to_redeem == 0) {
break;
} elseif ($amount_to_redeem < 0) {
// This should never happen, still if it happens, throw error
throw new Exception ("Something wrong with logic!");
exit();
}
// if we are here, that means some more amount left to redeem
}
Now, you can use two Update queries. First one would update amount_redeemed value against all the Credit id(s). Second one would Insert the Deduct row using the sum of all individual amount_redeemed value.
SELECT `id`, `email`, `NAME`, `type`,
(
( SELECT SUM(amount) FROM credit_table AS ct1 WHERE u.id = ct1.id AND process = 'ADD' AND date_exp > CURDATE()) -
( SELECT SUM(amount) FROM credit_table AS ct2 WHERE u.id = ct2.id AND process = 'Deduct' )
) AS balance
FROM
`user_table` AS u
WHERE
id = 2;
Hope it works as you wish
Related
This is a simple query that when executed updates the cash available by some users when their loans are due:
$sqlx = "UPDATE competitions
SET cash = (SELECT cash_after_deduct
FROM (SELECT l.competitions_id,
(c.cash-l.due_amount) AS cash_after_deduct
FROM loans l
JOIN competitions c ON l.competitions_id = c.id
WHERE l.due_date='2018-10-28'
GROUP BY l.competitions_id) q1
WHERE q1.competitions_id = competitions.id
)
";
The cash row of those users with a loan due on 2018-10-28 should be modified. And it works; however the cash row in users with different due dates are reset to 0, while they should remain unaffected.
Any idea on what can be wrong?
Many thanks in advance.
Your UPDATE query has no criteria to limit the scope of the update to only those affected by the due_date.
Additionally since you are not using an aggregate function on the loans table, MySQL is free to choose ANY single value from those that were grouped. This can lead to unexpected results.
To resolve the issue you can change the SET subquery to a JOIN. This will prevent unmatched records from the loans table from updating the competitions table with 0's. As well as reduce the number of queries that would need to occur, since using a subquery in the SET would require a query to be issued for each record in order to match the current row in competitions that is being updated by set.
Example: http://sqlfiddle.com/#!9/2a2c147/1
UPDATE competitions AS c
INNER JOIN (
SELECT l.competitions_id, SUM(l.due_amount) AS total_due
FROM loans AS l
WHERE l.due_date = '2018-10-28'
GROUP BY l.competitions_id
#optionally limit scope to those that have an amount due
#HAVING total_due > 0
) AS d
ON d.competitions_id = c.id
SET c.cash = c.cash - d.total_due
Data Set
competitions
---
| id | cash |
|-----|------|
| 1 | 5.00 |
| 2 | 2.00 |
| 3 | 0.00 |
loans
---
| id | competitions_id | due_amount | due_date |
|----|-----------------|------------|------------|
| 1 | 1 | 1.00 | 2018-10-19 |
| 2 | 1 | 1.00 | 2018-10-28 |
| 3 | 2 | 1.00 | 2018-10-28 |
| 4 | 1 | 1.00 | 2018-10-28 |
| 5 | 3 | 1.00 | 2018-11-19 |
Result
| id | cash | total_due | cash_after_deduction | loan_deductions |
|----|------|-----------|----------------------|-----------------|
| 1 | 5 | 2 | 3 | 2 |
| 2 | 2 | 1 | 1 | 1 |
This works by first retrieving the competitions_id and due_amount values from the loans table that are affected by the due_date.
The base competitions table updates are then limited by the INNER JOIN, which includes only the records that match those found within the loans table.
I used SUM as the aggregate function to ensure all of the due_amount records from all the loans for the competitions_id are totaled.
This looks like what you had intended, if not and you want a single due_amount, the query can be modified to match your desired results.
I was assigned to maintain the project that sells game item codes via the web app and deliver the codes via the text message to customer's mobiles. There is a problem that I still don't know how to solve it.
It simply occurs when the user purchases the product. They just click to puchase once but the app seems to process the purchasing stage for multiple times. So the users get a lot of items by paying for just one item.
Normally, the users have to add funds vi credit card to their accounts in order to have the sufficient balance to buy the product. So, this stage is conditional. Here is the brief code
<?php
public function actionPurchase() {
$user = Users::findOne(['mobile' => Yii::$app->session->get('mobile')]);
$product_price = Yii::$app->session->get('product_price');
$product_code = ProductStock::getCodefromPrice($product_price);
// Save the transaction log
$transaction = new Transactions();
$transaction->product_code = $product_code;
$transaction->amount = $product_price;
$transaction->user_id = $user->id;
$transaction->credit_before = $user->balance;
$transaction->created = date('Y-m-d H:i:s');
$transaction->save();
if ($user->balance >= $product_price) {
// Redeem the product from the API
$raw = ProductStock::redeem($product_code);
// Decode the JSON response
$response = json_decode($resp);
if ($response->status == 'Success') {
// Adjust the user balance
$new_credit = $user->balance - $product_price;
$user->balance = $new_credit;
$user->update();
// Send the SMS
Utilities::sendSMS($user->mobile, $response->item_pin);
return $this->redirect(['success']);
}
}
}
?>
As you can see that the I also record the transaction with user credit before and after the purchase. So if the purchase is success. I reduce the user balance from the user table and record the credit after to be the ducucted one.
Please note that the users are stored in the MySQL table along with their current balance. So, here is how the table looks like
| id | mobile | balance | created |
| 1 | 0811234567 | 300 | 2017-01-01 00:00:00 |
And the transaction table looks like this
| id | user_id | product_code | amount | credit_before | credit_after | created |
| 119687 | 1 | estr1203 | 100 | 300 | 200 | 2017-01-01 13:15:02 |
Hence, if the users successfully purchase the product they will have their balance deducted at the end.
But this is the result from the problem I am current encountering
| id | user_id | product_code | amount | credit_before | credit_after | created |
| 119691 | 1 | estr1203 | 100 | 200 | 100 | 2017-01-01 13:15:03 |
| 119690 | 1 | estr1203 | 100 | 200 | 100 | 2017-01-01 13:15:03 |
| 119689 | 1 | estr1203 | 100 | 300 | 200 | 2017-01-01 13:15:02 |
| 119688 | 1 | estr1203 | 100 | 300 | 200 | 2017-01-01 13:15:02 |
| 119687 | 1 | estr1203 | 100 | 300 | 200 | 2017-01-01 13:15:02 |
Please see the log creation time, they are the same. Normally, if the users click to purchase the product multiple times it will process the transaction multiple times too. So their balance should get deducted in sequence like 300 to 200 and the next time is 200 to 100 until they run out of balance and can no longer make a purhase. For the example above the correct transaction record should be
| id | user_id | product_code | amount | credit_before | credit_after | created |
| 119689 | 1 | estr1203 | 100 | 100 | 0 | 2017-01-01 13:15:02 |
| 119688 | 1 | estr1203 | 100 | 200 | 100 | 2017-01-01 13:15:02 |
| 119687 | 1 | estr1203 | 100 | 300 | 200 | 2017-01-01 13:15:02 |
But this looks like the app treats these simultaneous requests as the same one because it is the same user and all access the the if condition to check whether the user has sufficient balance at the same time. So the multiple items are sent to the user and they just click to purchase once.
Anyone can give me good ideas of how to handle such a problem? I don't know how to solve it by now and have been working on it for already couple days. Could it be a problem from the gap when the app call the API for the item code to be sent to the user and when the simultaneous requests from the same user come. The user's balance is not yet deducted until the product is successfully returned from the API. So the balance checking condition returns true. I got no idea on it. Becaause when I test it, it works properly.
Thank you in advance.
I Have 4 tables on my db
Table "User"
id | user
-----------
55 | Jhon
56 | Krish
57 | Boss
Table "Payout"
id | Payout_Date
------------------
1 | 31.10.2015
2 | 24.10.2015
3 | 17.10.2015
Table "Earning"
Userid | Date | Earning
------------------------------------
55 | 31.10.2015 | 5$
56 | 31.10.2015 | 1$
57 | 31.10.2015 | 3$
55 | 30.10.2015 | 5$
56 | 30.10.2015 | 12$
57 | 30.10.2015 | 0$
55 | 29.10.2015 | 5$
56 | 29.10.2015 | 4$
When I add a new Payout date (Payout_Date),
I want to find who earn >10$ in their Last payment date between new payout out date, If not pay before that user, his Last Payment_Date is No(get his all earning).
Then add that results to table "Payment" with new Payout_Date to Payment_Date. Their Last Payment_Date is From_Date.
Table "Payment"
id | Userid | From_Date | Payment_Date | Earning | Status
------------------------------------------------------------------
1 | 55 | 24.10.2015 | 31.10.2015 | 12$ | 0
2 | 56 | 24.10.2015 | 31.10.2015 | 17$ | 0
How to write that on Codeigniter Controller and Model?
You need to break the problem down into pieces: find current payout date, find last time user paid, add earnings since then, filter if > $10 .
Here is a sample of what a view may look like (I did not actually run this so there could be syntax errors)
SELECT Earning.Userid, sum(Earning.Earning) earning_since_last
FROM
/* Find current payout Date */
(SELECT MAX(Payout_Date) current_payout_date FROM PAYOUT) as curr_payout,
/* find last time user paid */
(SELECT Userid, MAX(Payout_Date) last_payout_date
FROM PAYOUT
GROUP BY Userid) last_payout,
Earning
WHERE Earning.date <= curr_payout.current_payout_date
and last_payout.Userid = Earning.Userid
and earning.date > last_payout.last_payout_date
GROUP BY Earning.Userid
HAVING SUM(Earning.Earning) >= 10
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!
I have a SQL table being created daily that is downloaded from a suppliers website,containing product info, that is in csv. I have everything creating alright and all the tables are identical. The problem that I am needing solved is that I need to compare the tables between today and yesterday (table names are the dates in following format mm-dd-yyyy) I need to compare a few different columns for different things.
I need to know all products that are in today's data that weren't in
yesterdays (can be checked by supplier SKU)
I need to know all product that were in yesterday's data that is no
longer in today's
I need to know when the price went up from yesterday's data
I need to know when the price has gone down from yesterday's data
I need to know when a sale has started based on yesterday's data as
well as stopped
These need to show the following labels in the table that will show the changes
regular up
regular down
miscillanious change (description change or change to a fields that aren't a priority)
promo on (discount added from supplier)
promo off (discount taken off by supplier)
delete (no record of the product in new list {probably been deleted})
new item (new record of product in new list)
out of stock
I have been searching everywhere for the answer for these issues and have found stuff that kind of shows me how to do this using union and join but I don't fully understand how to use them based on this scenario.
I have tried different PHP solutions by going through each piece of data and searching for the sku in the new table and vice versa then checking for any changes if they exist in both tables but this is taking a really long time and I have over 200 000 products in these tables. I am hoping that I can do these in less queries and by letting the sql server do more work then the php script.
Thanks for all the help!
Yesterday's Table
__________________________________________________________
| id | price | sale | description | qty | sku |
---------------------------------------------------------
| 1 | 12.50 | 0.00 | description product 1 | 12 | 12345 |
| 2 | 22.99 | 20.99 | describe the problem | 1 | 54321 |
| 3 | 192.99 | 0.00 | description ftw | 5 | 53421 |
| 4 | 543.52 | 0.00 | description | 15 | 45121 |
----------------------------------------------------------
Today's Table
__________________________________________________________
| id | price | sale | description | qty | sku |
---------------------------------------------------------
| 1 | 12.50 | 0.00 | description product 1 | 12 | 12345 |
| 2 | 22.99 | 0.00 | describe the problem | 1 | 54321 |
| 3 | 192.99 | 50.00 | description ftw | 5 | 53421 |
| 4 | 523.99 | 0.00 | description | 15 | 45123 |
----------------------------------------------------------
I need the new table to look like the following
_____________________________________________________________
| id | sku | label | description | price |
-------------------------------------------------------------
| 1 | 54321 | promo off | describe the problem | 22.99 |
| 2 | 53421 | promo on | description ftw | 192.99|
| 3 | 45123 | new item | description | 523.99|
| 4 | 45121 | delete | description | 543.52|
-------------------------------------------------------------
The following is the code I have for the deleted and new items currently. I am using int for the label/status in the example below and just signifying the different numbers.
$deleted = mysql_query("SELECT * FROM `test1`") or die(mysql_error());
while($skus= mysql_fetch_array($deleted))
{
$query = mysql_num_rows(mysql_query("SELECT * FROM `test2` WHERE SKU='".$skus['sku']."'"));
if($query < 1)
{
$tata= mysql_query("INSERT INTO `gday` (Contract_Price, SKU, status) VALUES (".$skus['price'].", ".$skus['sku'].", 1)");
}
}
$deleted = mysql_query("SELECT * FROM `test2`") or die(mysql_error());
while($skus= mysql_fetch_array($deleted))
{
$query = mysql_num_rows(mysql_query("SELECT * FROM `test1` WHERE SKU='".$skus['sku']."'"));
if($query < 1)
{
$tata= mysql_query("INSERT INTO `gday` (Contract_Price, SKU, status) VALUES (".$skus['price'].", ".$skus['sku'].", 2)");
}
}
EDIT:
The Following is the true table that all the data will be going into. I originally didn't want to muddy the water with the large table but by request I have included it.
ID
Status
DiscountDate
Price
Discount
DiscountEndDate
Desc1
Desc2
Desc3
Warranty
Qty1
Qty2
PricingUnit
PriceUpdate
Vendor
Category
UPC
Weight
WeightUnit
Because of the size of your database I could propose you an SQL solution.
When you work with a lot of data, PHP can be slow for several reason.
You can try to do some functions.
You just have to store the status data in an other table. This is the documentation to write a trigger.
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
Becareful if you have a lot of operation on your table I can suggest you to use PostgresSQL instead of mysql because I found it more simple to write function, trigger, ... using PL/sql
EDIT: Just have to write a simple function
I'm working on it at the moment. Think about using select case like in this answer
EDIT: Core function
DELIMITER |
CREATE PROCEDURE export()
BEGIN
(SELECT today.id, today.sku,
CASE today.price
WHEN today.price = yesterday.price THEN 'nothing'
WHEN today.price < yesterday.price THEN 'promo on'
ELSE 'promo off' END AS label
FROM today, yesterday WHERE yesterday.sku = today.sku)
UNION
(
SELECT today.id, today.sku,
'new item' AS label
FROM today LEFT JOIN yesterday ON yesterday.sku = today.sku WHERE yesterday.sku IS NULL)
UNION
(
SELECT yesterday.id, yesterday.sku,
'delete' AS label
FROM yesterday LEFT JOIN today ON today.sku = yesterday.sku WHERE today.sku IS NULL
);
END|
DELIMITER ;
To call just do:
CALL export();
Here is an example of possible core functions. Be careful in this case id could be the same. In the function you'll have to add a personal one in the first column.
If you need performance to display it faster in PHP, think about APC cache