I have a table called "allarmi_ingressi" in SQLite, with a lot of rows in it.
I want to create a query that changes the variable on my column "visto" to 1, if "visto=0", and to 0, if "visto=1".
This is what i made:
UPDATE allarmi_ingressi SET visto = '1' WHERE visto = '0'
Of course this modify every row in the column "visto";
I want to know if it's possible to modify it "selecting" it by the primary key, in my case "id_allarme".
In a SELECT query, you would use the WHERE clause to find rows with a specific id_allarme value.
The same WHERE clause can be used with UPDATE:
UPDATE allarmi_ingressi
SET visto = 1 - visto
WHERE id_allarme = ?;
Use CASE Expression
Query
update allarmi_ingressi
set visto = (
case visto when '1' then '0'
when '0' then '1'
else visto end
)
where id_allarme = __; -- id here
I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand.
For instance, three updates into 1 query:
UPDATE table_users
SET cod_user = '622057'
, date = '12082014'
WHERE user_rol = 'student'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '2913659'
, date = '12082014'
WHERE user_rol = 'assistant'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '6160230'
, date = '12082014'
WHERE user_rol = 'admin'
AND cod_office = '17389551';
I read an example, but I really don't understand how to make the query. i.e:
UPDATE table_to_update
SET cod_user= IF(cod_office = '17389551','622057','2913659','6160230')
,date = IF(cod_office = '17389551','12082014')
WHERE ?? IN (??) ;
I'm not entirely clear how to do the query if there are multiple condition in the WHERE and in the IF condition..any ideas?
You can do it this way:
UPDATE table_users
SET cod_user = (case when user_role = 'student' then '622057'
when user_role = 'assistant' then '2913659'
when user_role = 'admin' then '6160230'
end),
date = '12082014'
WHERE user_role in ('student', 'assistant', 'admin') AND
cod_office = '17389551';
I don't understand your date format. Dates should be stored in the database using native date and time types.
MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
cod_user=VALUES(cod_user), date=VALUES(date)
This assumes that the user_rol, cod_office combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list.
If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.
However, this approach makes prepared statements easier to build and more concise.
UPDATE table_name
SET cod_user =
CASE
WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END, date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
You can use a CASE statement to handle multiple if/then scenarios:
UPDATE table_to_update
SET cod_user= CASE WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END
,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
To Extend on #Trevedhek answer,
In case the update has to be done with non-unique keys, 4 queries will be need
NOTE: This is not transaction-safe
This can be done using a temp table.
Step 1: Create a temp table keys and the columns you want to update
CREATE TEMPORARY TABLE temp_table_users
(
cod_user varchar(50)
, date varchar(50)
, user_rol varchar(50)
, cod_office varchar(50)
) ENGINE=MEMORY
Step 2: Insert the values into the temp table
Step 3: Update the original table
UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET
t1.cod_office = tt1.cod_office
t1.date = tt1.date
Step 4: Drop the temp table
In php, you use multi_query method of mysqli instance.
$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";
$mysqli->multi_query($sql);
comparing result to transaction, insert, case methods in update 30,000 raw.
Transaction: 5.5194580554962
Insert: 0.20669293403625
Case: 16.474853992462
Multi: 0.0412278175354
As you can see, multiple statements query is more efficient than the highest answer.
Just in case if you get error message like this:
PHP Warning: Error while sending SET_OPTION packet
You may need to increase the max_allowed_packet in mysql config file.
UPDATE Table1 SET col1= col2 FROM (SELECT col2, col3 FROM Table2) as newTbl WHERE col4= col3
Here col4 & col1 are in Table1. col2 & col3 are in Table2 I Am trying to update each col1 where col4 = col3 different value for each row
I did it this way:
<update id="updateSettings" parameterType="PushSettings">
<foreach collection="settings" item="setting">
UPDATE push_setting SET status = #{setting.status}
WHERE type = #{setting.type} AND user_id = #{userId};
</foreach>
</update>
where PushSettings is
public class PushSettings {
private List<PushSetting> settings;
private String userId;
}
it works fine
I'm trying to recreate some code I did in SQL server on mySQL. I want to insert a row for every row in a table. I am using a loop to do this, in SQL server I used SELECT TOP #foo
here is my mySQl
begin
set #maxloop = (select max(id) from `LeagueInfo`);
set #loopno = 1;
while #loopno <= #maxloop DO
SET #mtop = (select `teams` * `homegames` from `LeagueInfo` where id = #loopno);
SET #div = (select `LeagueShortName` from `LeagueInfo` where id = #loopno);
SET #teams = (select teams from `LeagueInfo` where id = #loopno);
SET #homegames = (select homegames from `LeagueInfo` where id = #loopno);
SET #fthgsum = (select sum(`FTHG`)/#teams/#homegames from `footy` where `id` in(select`id`, `div` from `footy`
where `div` = #DIV
order by `matchdate` desc LIMIT #mtop));
SET #ftagsum = (select sum(`FTAG`)/#teams/#homegames from `footy` where `id` in(select`id`, `div` from `footy`
where `div` = #DIV
order by `matchdate` desc LIMIT #mtop));
insert into `looptable` (`di`, `homeav`, `awayav`) values (#div, #fthgsum,#fthgsum);
set #loopno = #loopno +1;
END while;
END;
I get an error on limit #mtop. I've read that I can get round this with a prepared statement but I'm not sure how to do it in a subquery. Is there a was to do this or is there another was I can select the top x amount of rows based on a value in another table for each row in that table.
Thanks
Paul
In your line of code,
SET #mtop = (select 'teams' * 'homegames' from 'LeagueInfo' where id = #loopno)
mtop is not a number, which is false since limit needs to be a number.
maybe you want to use "count(*)"?
I have a flag in my database called published, I set this to 1 for a published row. My question is , is there a way to set all other rows to 0 and set a particular row to 1 with just one query.
At the moment im using:
$db->query("UPDATE my_table SET published = '0'");
$db->query("UPDATE my_table SET published = '1' WHERE id = '$id'");
UPDATE my_table SET published = IF (id = $id,1,0);
Use a CASE Statement
UPDATE my_table
SET published = CASE
WHEN id = '$id' THEN 1
ELSE 0 END
In MySQL, there's no boolean type (conditions return an integer), so this works too :
UPDATE my_table
SET published = (id = $id);
id = $id returns 0 if $id is different than id, else 1.
I am trying to use a mysql case query to update multiple rows in a table. I have some cases which need to update the row with the same value. I was wondering whether it is possible to put all of these into one case or whether I have to create a new 'WHEN' for each?
Below is an example of what I am trying to accomplish but it obviously isn't the correct way to do this because I get an error.
UPDATE `groups` SET `status` = CASE `group_id`
WHEN 32 OR WHEN 33 THEN '1'
WHEN 31 THEN '2'
END
Is it possible to do something like that?
Thanks
I think you want
UPDATE groups SET status = CASE
WHEN group_id = 32 OR group_id = 33 THEN '1'
WHEN group_id = 31 THEN '2'
END
Edit You can use operators like BETWEEN. For example
UPDATE groups SET status = CASE
WHEN group_id BETWEEN 32 AND 33 THEN '1'
WHEN group_id BETWEEN 30 AND 31 THEN '2'
END
TRY
UPDATE `tablename` SET `status`= IF('group_id=31',2,1)
EDIT
UPDATE tableName SET `status` = IF( group_id IN (31, 32), 2, 1 ) WHERE section_id=1
OR
UPDATE tableName SET `status` = IF( group_id ANY (31, 32), 2, 1 ) WHERE section_id=1
running successfully on my table..what error u facing??
other syntax
UPDATE `tableName` SET `group_id` = CASE
WHEN group_id IN (31,32) THEN 1
WHEN group_id IN (33,34) THEN 2
END