SQL Update using values from other columns in same table - mysql

I have an SQL table, "data", with the following columns:
id (int),
date1 (datetime),
date2 (datetime),
difference (float)
What I would like to do is update this table so that the "difference" column contains the difference in years (as a float) between date2 and date1, only when date2 doesn't equal '0000-00-00 00:00:00'
I was thinking of something along the lines
Update data m
SET difference = datediff("hh",m.date2, m0.date1)/8765 --there are 8765 hours per year so this should give me my float
FROM data m0
WHERE m.id = m0.id
AND m.date2 <> '0000-00-00 00:00:00';
Yet when I try this I get an error stating "SQL syntax error. Check your MySQL server version for the right syntax to use near data SET difference = datediff("hh,m.date2,m0.date10/8765) from 'd' at line 1"
How would I modify my sql statement to get the desired results?
EDIT:
I am using xampp's phpMyAdmin interface to run this sql statement

Update statements are suppose to be on the form:
UPDATE table
SET column1 = expression1,
column2 = expression2,
...
WHERE conditions;
Your from clause is thus irrelevant.
You can use joins and sub select-queries though to link to other tables.
-- There are excellent demos on how to achieve that (actually, a complete duplicate):
UPDATE TABLEA a
JOIN TABLEB b ON a.join_colA = b.join_colB
SET a.columnToUpdate = [something]

I figured it out, thanks to Norbert's advice
I used
update data m, data m0
set m.difference = datediff(date(m.date2),date(m0.date2))/365
where m.id = m0.id
and m.date2 <> '0000-00-00 00:00:00';
I was using the incorrect syntax for mysql datediff, which takes 2 dates as a parameter and returns the difference in days.

Try this syntax for update with multiple tables:
Update data m, data m0
SET m.difference = datediff("hh",m.date2, m0.date1)/8765
WHERE m.id = m0.id
AND m.date2 <> '0000-00-00 00:00:00';
Note that in the SET statement you also need to indicate which table you are updating else it will still give you a nice warning.

Related

MySql - Update with Select

I need to update a table with a select inside. This is my query so far:
Update T_STATO_CASA
Set UTENTE = 'Admin'
Where ID_CASA in (
Select ID
From T_CASA
Where ID_RICHIESTA
In (437869, 437233, 437235, 437876)
)
But it returns the following error: "Subquery returned more than 1 value. This is not permitted when the subquery follows
=, !=, <, <= , >, >=
or when the subquery is used as an expression."
The subquery returns exactly 4 results if I run it separately. Is my syntax wrong? Thanks.
EDIT: all the suggested solutions that are using JOIN give me syntax error, as if MySql expects only the update-set-where command sequence. For instance I cannot write something like
update T_STATO_CASA as x
set [...]
where [...]
because it gives me syntax error: "Incorrect syntax near word AS. Expected SET"
UPDATE t_stato_casa x
JOIN t_casa y
ON y.id = x.id_casa
SET x.utente = 'admin'
WHERE y.id_richiesta IN(437869, 437233, 437235, 437876)
The reason is that your subquery will return more than one row of record
The more suitable way is to use JOIN instead
UPDATE T_STATO_CASA
JOIN T_CASA t
ON t.id = ID_CASA
AND t.ID_RICHIESTA
IN (437869, 437233, 437235, 437876)
SET UTENTE = 'Admin
If you still want to use subquery,you need to use group_concat to make the result into one record
This was the right syntax for my case:
UPDATE t_stato_casa
SET
UTENTE = 'Admin'
FROM
t_stato_casa AS sc
INNER JOIN T_CASA AS c
ON c.ID = sc.ID_CASA
WHERE
c.ID_RICHIESTA in (437869, 437233, 437235, 437876)
Thanks to everyone.

MySQL insert into column data from another table

I have 2 tables:
original {ID, FirstName, LastName}
and
dummy {ID(NULL), FirstName, LastName}
I have to insert into t2.ID the original.ID but only if the FirstName and LastName from both tables are the same. Now, i've tried:
1.Error Code: 1054. Unknown column 't2.FirstName' in 'where clause'
INSERT INTO dummy (ID)
SELECT ID
FROM original
WHERE dummy.FirstName = original.FirstName
AND dummy.LastName = original.LastName;
2.Error Code: 1054. Unknown column 'original.FirstName' in 'where clause'
UPDATE dummy
SET ID = original.ID
WHERE dummy.FirstName=original.FirstName
AND dummy.LastName= original.LastName;
3.Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
NOTE: I have to find a way without disableing safe mode.
UPDATE dummy
JOIN original
ON original.FirstName = dummy.FirstName
AND original.LastName = dummy.LastName
SET dummy.IDPacient = original.ID
WHERE original.ID <> 0;
Now if someone could help me understand what i did wrong in each of these 3 cases and/or give me a better solution, i would much appreciate the help.
Version 1 is just plain wrong - you'll insert a new row, not update the existing row.
Version 2 is close, you just need a join to "original":
UPDATE dummy
SET ID = original.ID
FROM dummy
INNER JOIN original
ON dummy.FirstName =original.FirstName
AND dummy.LastName = original.LastName;
You need to perform a join on first and last name between the "original" and "dummy" tables and then update the ID
Try this..
Update a
Set a.ID = b.ID
From dummy a
Join original b
On a.firstname = b.firstname
And b.lastname = b.firstname
You were trying to filter based on columns in the "original" table but it wasn't included in a from clause in your query.
This link might also have some more useful info for you if you need it.
SQL update query using joins

Delete duplicates for multiple columns in JOIN on same table

I am trying to make a delete from joined same table like this:
DELETE FROM `sp10_seo_url` AS sp1 JOIN
(
SELECT seo_url_pk, COUNT(*) AS maxc
FROM `sp10_seo_url`
GROUP BY seo_url_entity_type, seo_url_entity_id, seo_url_language_fk
HAVING maxc > 1
) AS sp2
ON sp1.seo_url_pk = sp2.seo_url_pk
However I am getting a mysql error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS sp1 JOIN ( SELECT seo_url_pk, COUNT(*) AS maxc FROM `sp10_s' at line 1
And I am not sure at all where the error is. The inner query runs just fine and returns the expected set of results. The "ON" keys are properly named (same since we are talking about the same table).
I guess the idea of the query is pretty clear (clean the table of different rows have the same set of values for the three "group by" columns. Is there another way to do this?
Thanks!
you can "cheat" mysql with a double indirection (as explained here Deleting a row based on the max value):
delete from `sp10_seo_url`
where seo_url_pk in (
select seo_url_pk from (
SELECT seo_url_pk
FROM `sp10_seo_url` sp1,
(
SELECT seo_url_entity_type, seo_url_entity_id, seo_url_language_fk
FROM `sp10_seo_url`
GROUP BY seo_url_entity_type, seo_url_entity_id, seo_url_language_fk
HAVING count(*) > 1
) sp2
where sp1.seo_url_entity_type = sp2.seo_url_entity_type
and sp1.seo_url_entity_id = sp2.seo_url_entity_id
and sp1.seo_url_language_fk = sp2.seo_url_language_fk
) t
);
http://sqlfiddle.com/#!2/899ff5/1

operation must use an updateable query - access

I want to update a table by using the join in access - 2007
UPDATE TABLE1 A INNER JOIN (SELECT ACCODE, SUM(AMOUNT) AS SUM_AMOUNT
FROM TABLE2 GROUP BY ACCODE) B ON A.ACCODE = B.ACCODE
SET A.TRIAL = A.TRIAL + SUM_AMOUNT
it gives me error that
operation must use an updateable query
i have try with below query and no error is here
UPDATE TABLE1 A INNER JOIN TABLE2 B ON A.ACCODE = B.ACCODE
SET A.TRIAL = A.TRIAL + SUM_AMOUNT
please help me to find what is wrong with first query
I think the reason Access treats your query as non-updateable is due to the subquery GROUP BY. You should be able to create an updateable query by using DSum.
UPDATE TABLE1 AS a
SET a.TRIAL = a.TRIAL
+ DSum("AMOUNT", "TABLE2", "ACCODE=" & a.ACCODE)
If ACCODE is text instead of numeric data type, add quotes around the value in the DSum expression.
UPDATE TABLE1 AS a
SET a.TRIAL = a.TRIAL
+ DSum("AMOUNT", "TABLE2", "ACCODE='" & a.ACCODE & "'")
I just had this issue and it was due to permissions on the table. I made a copy of the linked table to test my update query on, and kept getting this error message. I was pretty sure my query would be ok (it was a simple update) so I ran it on the actual table and I didn't get the error. Just wanted to add this for anyone else that comes across this in the future!
this error also comes when you are accessing database which is on different PC. so give write permission from security tab of folder and also give write access on sharing permission option.
In my case this is worked
Yes Mandeep, that is the way ms-access works.
UPDATE Table1 As T1 INNER JOIN Table2 AS T2 ON T1.F1 = T2.F1
SET T1.F2 = T2.F2
This query raises 'operation must use an updateable query' erro when T2 is a query, even when you are not updating T2.

Self-referencing updates in HQL

I have the following query in HQL:
update ProjectFile pf1
set pf1.validUntil.id =123
where pf1 = (
select pf from ProjectVersion pv, ProjectFile as pf
where pf.validFrom.sequence <= pv.sequence
and pf.validUntil.sequence >= pv.sequence
and pf.state <> 12
and pf.projectVersion.project.id = 1
and pv.project.id = 1
and pv.id = 12
and pf.id not in (2,3,4)
)
Hibernate parses the query correctly and generates SQL, but the database (MySQL) fails with error:
You can't specify target table 'ProjectFile' for update in FROM clause
The problem seems to be that the table to be updated is queried in the same context. Is there any way to rewrite the HQL query to produce SQL that can be executed in MySQL correctly? The other approach would be to create an intermediate table, which is what exactly I am trying to avoid.
I bumped into the same problem and posted a question here: MySQL/SQL: Update with correlated subquery from the updated table itself.
To solve your problem, you need to join at the UPDATE level, please take a look at the answer to my question.