SQL Query Update subtract variable - mysql

I am working on developing an inventory application. I have a table ShopInventory_Parts
When a user selects an item from the table, a window appears.
From here, the data from the item selected in the table is displayed in their respective fields. The last field is where the user is able to enter in the quantity that they will be "Checking Out" from the inventory.
When the user enters in the quantity checked out, I have a SQL script that will write to another table called ShopInventory_Parts_Checkout - and this is working correctly
My query for this is:
query = "INSERT INTO ShopInventory_Parts_Checkout (Name,Manufacturer,PartNum,assetID,quantityCheckedOut,t_stamp) VALUES (?,?,?,?,?,?)"
args = [Name,Manufacturer,PartNum,assetID,quantityCheckedOut,t_stamp]
result = system.db.runPrepUpdate(query,args)
My question is, how can I get the 'quantity' in my ShopInventory_Parts table to subtract from the quantity based on the user entry?
Right now, I have the following SQL query and it is returning "NULL"
query = "UPDATE ShopInventory_Parts SET quantity = (quantity - updatedQuantity) WHERE assetID=(?)"
args = [assetID]
result = system.db.runPrepUpdate(query,args)
I apologize if this seems very basic, but I just cannot get it working. Any help would be greatly appreciated.
Thank you

The Python variable needs to be in the args list, not the SQL. And pass the quantity being checked out, not the updated quantity (otherwise the two calculations cancel each other out).
query = "UPDATE ShopInventory_Parts SET quantity = quantity - ? WHERE assetID = ?"
args = [quantityCheckedOut, assetID]
result = system.db.runPrepUpdate(query,args)

Related

How can I write an SQL query that will checks if a column is zero it will update it and if its not, it will move to the next row?

DISCLAIMER: I'm still new to this website so I'm still learning the etiquette of the site, I apologize for any errors. Also, I previously posted a questions similar to this but some fantastic people recommended I rework my database to the current format. This was a great help however it was one step forward and one step back. I have an improved database but my question now continues to stand with a few minor tweaks.
To elaborate, I'm currently building an app that has the user create an account and login. Their information that they provided is saved into my database. My database contains two tables, one holds the users information, and one holds the users inventory, both are generated upon the completion of a create account GUI. For this question, only the second table is necessary. This table has three columns, the first is the users username, the second is their inventory slot number, and the third is the item id for the item that is in that slot. When the user creates an account, forty rows are created in this table, in each row their username remains constant. However, the slot number increments from one to forty and the item id column defaults to zero. Here is a visual representation:
Now to get to my code, when the user clicks a button, a random method gets called which sets an int variable which is current named "i" to a specific number. This number is the ID of an item in my app. At this point the user is prompted with two buttons that ask whether they want to keep the item or discard it. If they decide to keep the item I need it to be added to their inventory in the database. This is where my question comes into play. My app knows which user is logged in because when someone properly logs in the app sets their username (which is a primary key) to a global string variable which the rest of the app can user. so it knows which user to update but I need it to check through each of the rows in order, and if it finds a row with a zero in the ItemID column, it will update it to what the variable "i" currently is and end the query.
This is my current code, I'm very new to SQL but I'm trying to teach myself, I apologize if this offends you (because it's so bad):
EDIT: I've updated my code to this new query however I get an error that states java.sql.SQLException: You can't specify target table 'userinv' for update in FROM clause
try{
//get connection to database
Connection con = DataBaseConnect.getConnection();
//create a statement
PreparedStatement addInfo = con.prepareStatement("UPDATE userinv SET "
+ "ItemID = "+i+" "
+ "WHERE Username = '"+LoginController.userLog+"' "
+ "AND Slot = ("
+ "SELECT MIN(Slot) FROM userinv "
+ "WHERE ItemID = 0 "
+ "AND Username = '"+LoginController.userLog+"')");
//process result set
addInfo.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
at this point I know it needs to update the userinv table and I know it needs to do this where the users username is but I'm not sure how to write the code in between. Does anyone have any ideas?
This works in Oracle and should work for MySql:
update userinv set itemid = 815
where username = 'test'
and slot = (
select min(slot) from userinv
where itemid = 0
and username = 'test'
)
For more complex cases where you need the first row according to some ordering, but can't express this as a minimum this approach works on Oracle:
update userinv set itemid = 815
where username = 'test'
and slot = (
select slot from (
select count(*) over (partition by username order by slot) cnt,
slot
from userinv
where itemid = 0
and username = 'test'
) where cnt = 1
)
It uses analytic functions so it won't work on MySql, but there is an article how to fake them in MySQL.
With analytic functions, this should also work (didn't try, so it does contain typos and stuff)
update (
select count(*) over (partition by username order by slot) cnt,
u.*
from userinv u
where itemid = 0
and username = 'test'
order by slot
)
set itemid = 815
where cnt = 1
This accesses the table only once, which should be way faster when your table is huge.

MYSQL ORDER BY CASE stored value

Im trying to show first the value that is stored in the 'zone' field, since each customer has different value, I want the one in his ZONE to show first in his lists. Thanks
first run a query for using the VAR later
$data = "SELECT * FROM users;
$datas = mysqli_query($con,$data) or die(mysqli_error($con));
$query = mysqli_fetch_array($datas);
Now I can use the {$query['zone']} and show those first in the query
"SELECT * FROM users WHERE ORDER by zone CASE zone WHEN '{$query['zone']}' THEN 0 ELSE 2'";
Im not getting the expected results, any advice? Thanks
I think you want something like this:
ORDER by (zone = '{$query['zone']}') desc,
zone
This assumes that the expression '{$query['zone']}' is the zone that you want to give priority to. User's whose zone's match this will appear first.

MySQL Get "id" from select

I have a select statement:
SELECT id, content, name
FROM records
WHERE type = '1'
AND name = 'test';
Here's the output:
id content name
99708 10.6.252.41 server01.example.org
What I'd like to do is be able to get the id that is returned from the previous statement and USE the id as input into another statement (an UPDATE statement) that will increment the value of a single column in the same table.
An example UPDATE statement that I am wanting is:
update records SET hits = hits + 1 WHERE id = ID_FROM_SELECT;
Thanks in advance.
You can use user defined session variables for this if the SELECT is returning just one result:
SELECT #id:=id AS id, content, name
FROM records
WHERE type = '1'
AND name = 'test';
Then, on the same database session (connection), do the following:
UPDATE records
SET hits = hits + 1
WHERE id = #id;
I'm assuming you're doing something with the selected records in your app, and you're trying to save on performance by avoiding having to search for the record again in the UPDATE. Though, in that case, why not set the 'id' value as a parameter in code?
Obviously, if the SELECT is returning multiple records, this would best be done in code as I mentioned above, otherwise you're left with running the SELECT query again as a subquery:
UPDATE records
SET hits = hits + 1
WHERE id IN
(SELECT id
FROM records
WHERE type = '1'
AND name = 'test');
So, then, it makes more sense just to apply the same filter to the UPDATE instead:
UPDATE records
SET hits = hits + 1
WHERE type = '1'
AND name = 'test'
Probably this is not what you want to do.
First of all...If the query only returns 1 line, the solution provided by Marcus Adams works fine. But, if the query only returns one line, you dont need to preset the id in order to update. Just update it:
update records
set hits = hits + 1
where type = '1'
and name = 'test'
Second...If the query will not return only one record and you want to update all records returned with same values or calculations, the same code above will do what you need.
Third, if the query does not return just one record and you need to update each record returned with different value then you need to have a different approach.
I think you are not designing your system very well. If the request for update come from outside, you should have the id to be updated as a parameter of your request. For example something like:
<html>
<body>
Test
</body>
</html>
And in your update.php you have something like:
<?php
$id = $_GET['id'];
$sql = "update records set hits = hits + 1 where type = '1' and name = 'test' and id = $id";
?>
Of course, the picture I have is to small. Probably you have a reason to do this way or this is just an example. If you fill us up with more info we might be more helpful.

Getting values from one table to another in ASPMaker

I am using ASPMaker. It's a Classic ASP code generator. I am using MySQL database as well:
I am trying to get values from one table to another here's the code used to get the value from table1:
Dim Balance
Balance = ew_ExecuteScalar("SELECT Balance FROM [Balance] " )
ListOptions.GetItem("Balance").Body = Balance
The problem is that I am getting only the last value for all records in the table. For example if the last [Balance] = 700, all the records in the table have [Balance] = 700.
Any idea?

Setting parent record field value based on Maximum Child record field value

I am working with MS Access 2007.
I have a table called [tblDonors] linked to child records in a table called [tblReceipts].
I am trying to set the value of a new Boolean(y/n) field [tblDonors].[blInactive]. I would like to run a script which goes through every record in [tblDonors] and set the [blInactive] field to "True" if the most recent receipt year([tblReceipts].[Date]) is older than year(now())-2.
Here is my query:
SELECT tblDonors.ID, Year([tblReceipts].[Date]) AS [Year], tblDonors.Active
FROM tblDonors LEFT JOIN tblReceipts ON tblDonors.ID = tblReceipts.ID
WHERE (((Year([tblReceipts].[Date]))>=Year(Now())-2))
ORDER BY Donors.ID;
This query shows the parent record multiple times if the donor has donated more than once within the past two years, which creates duplicate records in a report.
How can I go through each record of this query to set tblDonors.Active to TRUE using VBA?
The following helps demonstrate the gist of what I am attempting to accomplish.
Function fnActivity() 'locates active donors
For each record in recordset 'Go through each record in the query...
record.[Active].Value = True '...and flag as active member.
Next record
End Function
It seems to me that you could accomplish that by setting [blInactive] to Yes for everyone...
UPDATE tblDonors SET blInactive = Yes
...and then update the current donors like this:
UPDATE tblDonors SET blInactive = No
WHERE ID IN
(
SELECT ID FROM tblReceipts
WHERE Year([tblReceipts].[Date]) >= (Year(Now()) - 2)
)