Mysql change one column value based on another column - php

I have an auto increment column. I want to change value of another column based on this auto increment column value.
another column value ==> (auto increment column value/3) +1
How do I do it via query? Is it possible?
I want to do it for newly creating rows.

Is the new (id/3)+1) value ever going to change?
Judging from the question, the data only exists at the time of the insert. The auto increment column will never change as it has to be a Primary Key, I would only insert on it if you have to join on it or if it is going to change in future. You can get this derived value from a SELECT query after your insert.
SELECT id, ((id/3)+1) as derived value from table;

It is a "derived" value and you should consider not to store this value but calculate it in your PHP code every time you need it. Here is a post where you can find further explanations about when to store derived values: Storing “derived” values vs calculating them on extraction
#Octopi solution could solve your problem.

Try the following:
INSERT INTO your_table (your_column)
SELECT (MAX(auto_increment_column) / 3) + 2 FROM your_table;
EDIT
If you want to calculate the column depending on the number of values use this:
INSERT INTO your_table (your_column)
SELECT (COUNT(*) / 3) + 2 FROM your_table;
EDIT 2
You can accomplish the same using:
INSERT INTO your_table (your_column) VALUES (
(SELECT (MAX(aa.auto_increment_column) / 3) + 2 FROM your_table AS aa)
);
EDIT 3
For more columns you can use something like this:
INSERT INTO your_table (your_column, some_other_column) VALUES (
(SELECT (MAX(aa.auto_increment_column) / 3) + 2 FROM your_table AS aa), some_other_column
);
You can find more info here:
Select from same table as an Insert or Update
In fact you have to add +2 because it's 1 from you rule and +1 to increment the MAX(id).

Related

How should I update a MySQL table column with the average of other two columns?

I have a table with the following columns: id (AI, PK), name, surname, group, grade1, grade2, average and I must insert from a PHP script the average value of 'grade1' and 'grade2' in the 'average' column.
I have used:
INSERT INTO `table_name`(`average`) SELECT AVG((`grade1` + `grade2`)/2.0) FROM table_name GROUP BY `id`
I have the grades inserted, but somehow when I run the SQL statement, it creates new rows only with the average values. I need to UPDATE the column 'average' in the existing rows, not create new ones.
Thank you in advance!
You seem to want update, not insert:
update table_name
set average = (grade1 + grade2) / 2;
I should note that having such a calculated column is dangerous, because it can get out-of-synch. Much safer are generated columns, which you can express as:
alter table table_name add column average decimal(10, 2)
generated always as ( (grade1 + grade2) / 2);
This is calculated when the value is queried so it is always up-to-date.
You should use UPDATE ... WHERE ... instead of INSERT INTO ...
I would also consider to use a trigger instead of using PHP.

Insert distinct records in the table while updating the remaining columns

This is actually a form to update the team members who work for a specific client, When i deselect a member then it's status turns to 0.
I have a table with all unique records. table consists of four columns -
first column is `id` which is unique and auto_incremented.
second column is `client_id`.
third column is `member_id`. (these second and third columns together make the primary key.)
fourth column is `current` which shows the status (default is 1.).
Now i have a form which sends the values of client_id and member_id. But this forms also contains the values that are already in the table BUT NOT ALL.
I need a query which
(i) `INSERT` the values that are not already in the table,
(ii) `UPDATE` the `current` column to value `0` which are in the table but not in the form values.
here is a screenshot of my form.
If (select count(*) from yourtable where client_id = and member_id = ) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
First of all check if the value exists in the table or not, by using a SELECT query.
Then check if the result haven't save value so it will be inserted, else show an error .
This would be a great time to create a database stored procedure that flows something like...
select user
if exists update row
else insert new row
stored procedures don't improve transaction times, but they are a great addition to any piece of software.
If this doesn't solve your problem then a database trigger might help out.
Doing a little research on this matter might open up some great ideas!
Add below logic in your SP
If (select count(*) from yourtable where client_id = <value> and member_id = <value>) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
if you want simple solution then follow this:
*) use select with each entry in selected team.
if select returns a row
then use update sql
else
use insert sql.
In your case member_id & client_id together makes the primary key.
So , you can use sql ON DUPLICATE KEY UPDATE Syntax.
Example:
$sql="INSERT INTO table_name SET
client_id='".$clientId."',
member_id='".$member_id."',
current='".$current."'
ON DUPLICATE KEY
UPDATE
current = '".$current."'
";
In this case when member_id & client_id combination repeats , it will automatically executes update query for that particular row.

Incrementing a field in a database

I've never had or attempted to do this before, but what I want to do is instead of getting the value out of the database and adding 1 to it just to do an update query is just do one UPDATE query and incrementing the field...
Is there a way of using a JOIN query to get the current value and then updating it again with the new one?
As it's literally just incrementing an INT number I thought there may be way around it.
update table_name set field_name=field_name + 1 where <condition>;
You could just do the following:
UPDATE table_name set field_to_increment = field_to_increment + 1 WHERE <cond>
Use this:
UPDATE yourtable SET yourcolumn = yourcolumn+1 WHERE yourid=123;
It's easy to increment a value in a cell:
UPDATE table SET column = column + 1 WHERE id = 123;

MySQL: Adding figures during UPDATE

I'm trying to UPDATE a column for a user, so that they can only ADD a value to the existing value. So for example, if the table looked like this:
UserID 3
Total 12
User adds 4, so it's changed to:
UserID 3
Total 16
I could obviously do this by doing a query, getting the column value, adding it to the new value, and then updating that column... but I was wondering if there was a way to do it without using a SELECT statement first. Perhaps something using SUM()?
So the query might go:
UPDATE Users SET Total=SUM(Total + :total) WHERE UserID = :userID;
If so, what's the correct syntax?
Thanks!
It's as simple as:
UPDATE Users SET Total = Total + :total WHERE UserID = :userID;
You don't need the SUM() since you are just adding the values, SUM() adds the values of a column together.
UPDATE Users
SET Total= Total + :total
WHERE UserID = :userID;

How get incremented value from table

I need to get next id from table (auto_increment).
I could just use SELECT * from table ORDER BY id DESC LIMIT 1;
For example I get 50. But if we delete from table two items I will get 48 but correct one
will be 51. How get correct value even we something delete from table ?
You can only use SHOW TABLE STATUS LIKE 'tablename' to fetch the auto_increment value. A simpler solution might be: SELECT MAX(id) + 1 FROM table, but this is buggy if the last entry was deleted.
show table status like 'table_name'
next id value is in 'Auto_increment' field
SHOW TABLE STATUS LIKE 'table'
The value you want is in the Auto_increment field.
Be careful about concurrency though: by the time you get around to using this value, some other client could have inserted into the table and thus your value is out of date. It's usually best to try to not need this.
SELECT LAST_INSERT_ID() + 1;
gets the last ID used in an insert in an autoincrement column + 1
I see two solutions for the next ID:
1) Select bigger value of a column with max function. Example: select max( id ) from table;
2) Using the command SHOW STATUS LIKE and get the correct index of array. Take a look: http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html
Seems to me you're creating a race condition here.
Why exactly can you not insert the row you want to insert and then use LAST_INSERT_ID() to find it's ID?

Categories