Table Update- Calculated Field [duplicate] - ms-access

I have Two tables in my access database
table1(ID,productname,qunatity,remainder)
table2(ID,productname,sales)
these tables are related together using "product name" ,How can I update"reminder" from table1 with the value of "quantity form first table - Sum(sales) from second table"

Because update queries in MS Access require updateable status, you cannot use a direct inner join on an aggregate query. Consider using the MS Access DSum() function:
UPDATE table1
SET table1.remainder = table1.quantity -
DSum("Sales", "table2", "ProductName='" & table1.ProductName & "'")

Perform an update join by getting the SUM() first like
UPDATE a
SET a.remainder = x.SaleTotal
FROM table1 a
INNER JOIN (SELECT productname, SUM(sales) AS SaleTotal
FROM TABLE2 GROUP BY productname) x
ON a.productname = x.productname;

When you say that it's linked by the productname field please tell me in table 1 that is a foreign key. Since you already have an ID in table 2 there's no reason not to use that ID as the foreign key in table 1.
If you were to do that the update would be as simple as this:
update table1
set table1.quantity = table1.quantity - SUM( table2.sales )
from table1
inner join table2 on table1.productID = table2.productID
where table1.productID = 1;

Related

Update field set to value of row in same field

I'm trying to update a specific field and set it equal to value of a row in the same field.
What have I tried so far is this:
mysql> UPDATE tblitem SET imagefilename = (SELECT imagefilename from tblitem where itemid=2) where itemid=1'
1093 - You can't specify target table 'tblitem' for update in from clause
What I am trying to do here is to update the value of itemid 1 to the value of itemid 2.
Is that even possible? Thank you in advance.
In MySQL, if you're doing an UPDATE/INSERT/DELETE queries on a table, you can't reference the said table in the inner query. One workaround is to use a subquery inside the inner query:
UPDATE tblitem
SET imagefilename =
(
SELECT imagefilename
FROM (SELECT * FROM tblitem) AS t
WHERE itemid = 2
)
WHERE itemid = 1
Use a join instead:
UPDATE tblitem t JOIN
(SELECT imagefilename from tblitem where itemid = 2
) t2
SET t.imagefilename = t2.imagefilename
WHERE itemid = 1;
The SQL standard and other databases allow you to refer to the table being updated elsewhere in the update statement. However, MySQL does not allow this. The JOIN is a simple enough work-around.

MySQL: delete rows with "WHERE ... NOT IN" from only one single table

In a MySQL database I have a many-to-many relationship between two tables. For the sake of simplicity let's assume those tables map homes and their residents. I have a third table to map those relations (home_resident_relations). The latter table has an additional column datemodified that stores the date of the latest update of each row via triggers.
Now I want to get rid of all former residents for each home and only keep the current ones - that is those with the newest date.
I have already a working SELECT clause that will list me all old relations I want to delete:
SELECT * FROM `home_resident_relations` WHERE `resident_id` NOT IN
(SELECT tbl.`resident_id`
FROM `home_resident_relations` tbl
WHERE tbl.`datemodified` =
(SELECT max(tbl2.`datemodified`)
FROM `home_resident_relations` tbl2
WHERE tbl2.`home` = tbl.`home`
GROUP BY tbl2.`home`)
OR tbl.`datemodified` IS NULL
);
Now it would be a straight-forward idea to simply replace the SELECT * with a DELETE command to remove all those rows. However, this does not work due to error
#1093 - You can't specify target table 'home_resident_relations' for update in FROM clause
So here's my question:
How do I delete from a table while using it in the WHERE ... NOT IN clause?
Use a left join instead:
DELETE hrr
FROM `home_resident_relations` hrr LEFT JOIN
(SELECT tbl.`resident_id`
FROM `home_resident_relations` tbl
WHERE tbl.`datemodified` = (SELECT max(tbl2.`datemodified`)
FROM `home_resident_relations` tbl2
WHERE tbl2.`home` = tbl.`home`
GROUP BY tbl2.`home`
) OR
tbl.`datemodified` IS NULL
) tt
ON hrd.resident_id = tt.resident_id
WHERE tt.resident_id IS NULL;
This works for both the SELECT and DELETE.
Try using DELETE with join:
DELETE FROM `home_resident_relations`
LEFT OUTER JOIN
(SELECT tbl.`resident_id`
FROM `home_resident_relations` tbl
WHERE tbl.`datemodified` =
(SELECT max(tbl2.`datemodified`)
FROM `home_resident_relations` tbl2
WHERE tbl2.`home` = tbl.`home` )
OR tbl.`datemodified` IS NULL) s
ON(s.`resident_id` = `home_resident_relations`.`resident_id`)
WHERE s.`resident_id` is null

join with latest records only from another table:- Remove replication

I have 2 table lets say table1 and table2 table 1 is the master data and table 2 is child. I have to find out records from both table corresponding to the given table1.id. But there are more than 1 record in table2 corresponding to table1.id. So I would like to filter the latest record first from table2 corresponding to table1.id then apply the join on filtered data from table2 and table1.
table1= location_grids
table2= local_ads
Following what I am doing ?
SELECT * FROM `location_grids`as l
LEFT JOIN `local_ads` la ON `la`.`location_grid_id` = `l`.`id`
Inner join (SELECT id, location_grid_id, max(booked_till) as maxbooked
from local_ads group by location_grid_id ) as b
on la. location_grid_id = b.location_grid_id
and la.booked_till = b.maxbooked
WHERE `l`.`location_id` = '1'
AND `l`.`flag` = 1
The query is returning me unfiltered data. How can I filter then apply join on data. Any help will be appreciated.
table1:- location-grid
table2:- local_ad
Finally got the solution :- I was searching for following query.
SELECT location_grid_id, user_id, booked_from, booked_till, purpose, category, duration, price, MAX( created )
FROM local_ads
GROUP BY location_grid_id
Here I wanted to run join with latest record of the particular id as many record must be exist in local_ads

SQL Select Column 'Name' in 3 Tables

"I have 3 Tables which is Admin table,Studentinfo Table and Useraccount Table.
i want to join that 3 tables for my search engine. :(
im beginner in sql anyone can help me?"
SELECT Username,Name,Position,Status,ImageName FROM useraccount
JOIN admin ON admin.username = useraccount.username
JOIN studentinfo ON studentinfo.username = useraccount.username
where Name Like '%Search%';
"That is my code but nothing happen."
When dealing with multiple tables you would have to compensate for column name ambiguity as the same column name could be available in other joining tables and there is no way for the query execution engine to know which one you want returned.
You can easily fix this by adding an alias or table name to referenced column Name
TableAlias.ColumnName
( or )
TableName.ColumnName
Example:
SELECT Col1
FROM table1
JOIN table2
ON table1.Col1= table2.Col2
Will generate a Ambiguous column name error.
SELECT t1.Col1
FROM table1 t1
JOIN table2 t2
ON t1.Col1= t2.Col2
Or
SELECT table1.Col1
FROM table1
JOIN table2
ON table1.Col1= table2.Col2
The changes:
Added the prefix "t1" or "TableName" to the requested column, so that the engine knows which table we want the data from
Added table aliases in the FROM / JOIN clauses to shorten the code
Scenario Example:
SELECT <TableName>.Username,
<TableName>.Name,
<TableName>.Position,
<TableName>.Status,
<TableName>.ImageName
FROM useraccount
JOIN admin
ON admin.username = useraccount.username
JOIN studentinfo
ON studentinfo.username = useraccount.username
WHERE <TableName>.Name LIKE '%Search%';

Delete, Update with derived tables?

I have just studied FROM clause and derived tables in mysql and most of the websites provided the examples using SELECT command
Example SELECT * FROM (SELECT * FROM usrs) as u WHERE u.name = 'john'
But when I have tried using delete or update command it does not seem to work.
Example DELETE FROM (SELECT * FROM usrs) as u WHERE u.name = 'john'
1064 - 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 (SELECT * FROM usrs) as u WHERE u.name = 'john' at line
UPDATE (SELECT * FROM usrs) as u SET u.lname ='smith' WHERE u.name = 'john'
1288 The target table e of the UPDATE is not updatable
So derived tables does not work with delete or update commands? or is there a way to make it work.
Instead of writing the table name for update and delete I want to write a subquery that gets the records and perform the delete operation on that records? Is that possible in mysql?
UPDATED I have to delete a record and i have three tables, the record may exist in any of the table
My approach delete from first table rows effected? quit: else check second table rows effected? quit : else check third table
But if I use UNION ALL I can do this way
Delete from (select * from tb1 union all select * from tb2 union all select * from tb3) e as e.uname = 'john'
but this query does not seem to work , now could anyone tell me how do i delete or update a record when i have more than one table to search. Any help is greatly appreciated.
You can't directly delete from the subquery, but you can still use it if you'd like, you'll just need to use it in a JOIN:
DELETE usrs
FROM usrs
INNER JOIN (
SELECT * FROM usrs WHERE name = 'john'
) t ON usrs.Id = t.Id
Or you could use IN:
DELETE usrs
WHERE ID IN (
SELECT ID
FROM usrs
WHERE name = 'John'
)
With this said, for this example, I don't know why you'd want a subquery:
DELETE usrs WHERE name = 'John'
Edit base on comments. To delete from multiple tables at the same time, you can either have multiple DELETE statements, or you can use something like the following:
delete t1, t2, t3
from (select 'john' as usr) t
left join t1 on t.usr=t1.usr
left join t2 on t.usr=t2.usr
left join t3 on t.usr=t3.usr
SQL Fiddle Demo
Derived tables exist only for the duration of the parent query they're a member of. Assuming that this syntax and the operations were allowed by MySQL, consider what happens:
a) Your main query starts executing
b) the sub-query executes and returns its results as a temporary table
c) the parent update changes that temporary table
d) the parent query finishes
e) temporary tables are cleaned up and deleted
Essentially you'll have done nothing except waste a bunch of cpu cycles and disk bandwidth.
UPDATE queries DO allow you to join against other tables to use in the WHERE clause, e.g..
UPDATE maintable
LEFT JOIN othertable ON maintable.pk = othertable.fk
SET maintable.somefield='foo'
WHERE othertable.otherfield = 'bar'