mysql update math - mysql

say p.products_price equals 1
why does:
UPDATE products p
SET p.products_price = (1 + p.products_price)
WHERE p.products_id = 8
make p.products_price equals 3?
It is adding 1 to the price and then doing it all over again? I am trying to do something a little more complicated but when it didn't work I broke it down to the simplest thing ever. Can I make some kind of temporary value here and calculate the new price and then set it to that?
Please help I am raging,
Thanks.
MySQL client version: 4.1.22
edit: the column is decimal type, i tried the same update on an int column with the same result.
edit: this is not running in code so there is no chance of the code calling the same update twice

UPDATE products
SET products_price = (1 + products_price)
WHERE products_id = 8
works like it should (removed table alias 'p')

Your SQL looks fine. Is the 'something' column unique? Make sure that you are only updating a single record.

That should definitely set products_price to 2. There must be something else going on.
This is similar to Problem with updating a MySQL field with PHP but there was no good solution there so I'll leave this one open too.
Are you running it from the client, or through a script?
Do you have any transactions open or other scripts accessing the database?
Edit: You mentioned joins in your comment - I'd be willing to bet that your join is pulling back the same row more than once.

Related

Switch values in MySQL table

I have a table in MySQL with a field "Ordering" These are just auto incremented numbers. Now I wonder if there is a query to change the values from the last to the first...
So the entry with ordering 205 should become 1, 204 -> 2 and so on...
It's actually not an auto-increment. The problem is I started adding projects from the current website. From page 1 to page 20, but the first item on page 1 is the latest. The way I added the new projects, the newest is on the last page..
If the ordering field is switched, the new items added will be correctly numbered again and added to the front page. It's just a wrong way I started adding old projects...
Structure
Examples of the content
I can't comment due to limitations, but i really agree with #Abhik Chakraborty.
You don't want to do this. Just use the order by as he suggested.
Example:
SELECT * FROM tableName
ORDER BY columnName DESC;
Just in case you would like to know more about it: http://www.w3schools.com/sql/sql_orderby.asp
Try this as one statement call:
SET #MaxSort := (SELECT MAX(Ordering) FROM MyTable);
UPDATE MyTable t set t.Ordering = (#MaxSort + 1 - t.Ordering);
This will work if field doesn't have unique constraint.
But this field, should not be an auto_increment field at first place. Auto increment is increasing NOT decreasing counter. Except if you just try to fix existing data and the new records will be increasing.
Additional explanation
Thanks for pointing it out. Multiple query inside single query statement doesn't work with php_mysqli and it is not used because of potential MySQL injection attack if servers allows it. Maybe you can setup PHPMyAdmin to use PHP PDO.
I can use multiple queries, but I'm using PHP PDO or DBeaver database manager.
I can only suggest to supply MaxSort manually (since this is one time job anyway):
UPDATE
MyTable t
set
t.Ordering = 254 - t.Ordering + 1;

SQL update from one Databse to another based on a Title match

I just finished migrating my WordPress database, everything went right.
Until I realise that I got a serious issue the posts ID changed after this processes
And I’m using the posts ID on my URLs and I want to keep using it to don’t lose
my old links.
I still have both databases (old & new) and I want to know how I can update the ID from old one to the new one matching the title?
Something like:
Update newbase table ID from oldbase table id where oldbase title = newbase title
:p something like that :d
Thanks for help.
Translating the pseudo-code into SQL should do the trick:
UPDATE newdb.tablename AS n
INNER JOIN olddb.tablename AS o ON n.title=o.title
SET n.id=o.id;
Caveat
You might run into duplicate id values, so you might want to move them first
SELECT #oldmax:=MAX(id) FROM olddb.tablename;
SELECT #newmax:=MAX(id) FROM newdb.tablename;
UPDATE newdb.tablename SET id=id+#oldmax+#newmax;

SQL update query for balances using Access raises 'Operation must use an updateable query'

I have the following query (MS Access 2010) which I'm trying to use to update a table with a running balance:
UPDATE Accounts a SET a.CurrentBalance =
(SELECT sum(iif(c.categoryid = 2,t.Amount * -1, t.Amount)) +
(select a1.openingbalance
from accounts a1 where a1.accountid = a.accountid) AS TotalAmount
FROM transactions t inner join (
transactiontypes tt inner join
categories c on c.categoryid = tt.categoryid)
on t.transactiontypeid = tt.transactiontypeid);
The tables used are:
A work around for the "Query must use an updateable query" is to use a temporary table and then update the final target data based on the aggregated data in the temporary table. In your case, as mwolfe suggests, you have an aggregate function in the inner select query. The workaround could provide a quick fix for this situation, as it has for me.
Ref: http://support.microsoft.com/kb/328828
This article helped me understand the specifics of the situation and provided the work around:
http://www.fmsinc.com/MicrosoftAccess/query/non-updateable/index.html
You cannot use aggregate functions (like SUM) in an update query. See Why is my query read-only? for a full list of conditions that will cause your query to be "non-updateable".
The Access db engine includes support for domain functions (DMax, DSum, DLookup, etc.). And domain functions can often allow you to circumvent non-updateable query problems.
Consider DSum() with these 3 rows of data in MyTable.
id MyNumber
1 2
2 3
3 5
Then in the Immediate window, here are 2 sample DSum() expressions.
? DSum("MyNumber", "MyTable")
10
? DSum("IIf(id=1,MyNumber * -1, MyNumber)", "MyTable")
6
I think you may be able to use something like that second expression as a replacement for the sum(iif(c.categoryid = 2,t.Amount * -1, t.Amount) part of your query.
And perhaps you can use a DLookup() expression to get your TotalAmount value. Unfortunately I got frustrated trying to translate your current SQL to domain functions. And I realize this isn't a complete solution, but hope it will point you to something useful. If you edit your question to show us brief samples of the starting data and what you hope to achieve from your UPDATE statement based on that sample data, I would be willing to have another look at this.
Finally, consider whether you absolutely must store CurrentBalance in a table. As a rule of thumb, avoid storing derived values. Instead, use a SELECT query to compute the derived value when you need it. That approach would guarantee CurrentBalance is always up-to-date whenever you retrieve it. It would also spare you the effort to create a working UPDATE statement.

Simple like SQL statement failed

I know this might shock some but I just cant figure out what's wrong with this SQL statement.. it kills my head.
SELECT * FROM groups WHERE gname LIKE '%m%';
I am using mysql 5.1.41
If you don't get any rows back, perhaps that's the right answer. Mistakes usually happen when your assumptions don't match the situation at hand.
Are you sure you have values in the gname column with lower case 'm' in them?
Are you sure you're running the query against the database you think you are?
This statement will retrieve every column and every row from the groups table where the gname column contains a lowercase m somewhere. Is this what you wanted to achieve?

MySql skips first record found

in my database i have 10 records with almost exact same data , they differ only by one field ( the field is not in the query) and when i run the following query
SELECT * FROM friends WHERE user_id= 'MyUserName' AND follow_back = 0 AND until_date= '2009-10-13' LIMIT 12
it shows only 9 records , any one stumbled upon similar problem ?
Thanks & waiting for your answers !
The short answer is there's nothing wrong with your query, so
user_id!='MyUserName'
or
follow_back != 0
or
until_date != '2009-10-13'
Try just querying on one criterion at a time and see if you can norrow it down. Perhaps follow_back is NULL?
When trying to debug problems like these, what I would usually do is to try solving it using a divide and conquer approach.
So try and remove one where condition at a time, then execute the query. That way you will be able to isolate the offending condition.
Good luck
Are you sure, that all values in column user_id are the same? Maybe that one missing record has user_id = 'MyUserName ' (note the space).
I had the same problem a minute ago. It turned out it wasn't the query that was the problem, but the IF where I check if anything's returned. Might want to check that.