MySQL: trouble copying data from one table to another based on matching ids - mysql

i need to copy existing data from one table to another based on matching fields. this is not a wholesale column dupe.
how it should work is: if the id in asset matches the assetID in report, then copy the repEmail field from the report table into the rep_email field in the asset table. this is what i've built based on the MySQL docs for insert...select:
INSERT INTO asset (rep_email)
SELECT report.repEmail
FROM report WHERE report.assetID = asset.id
this throws: Error in query (1054): Unknown column 'asset.id' in 'where clause'.
i also tried this:
where safety_report.eNumber = asset_roster.id
insert into asset_roster (building_rep_email)
select bldgRepEmail from safety_report;
but it errors on the first line. :(
i'm not sure how to modify this to eliminate the error and properly write the values across. it seems like it should be a simple operation... please advise.
NB: i do not have admin access to the tables. the reason for this seeming duplication has to do with permissions to the different tables. and even if not, i'd need to write foreign keys anyway...

I think that you want to update the column rep_email of asset with values from the column repEmail of report:
UPDATE asset a
INNER JOIN report r ON r.assetID = a.id
SET a.rep_email = r.repEmail

Related

MySQL Command what does a point mean?

I'm a newbie in mysql and have to write a implemention for a custom mysql asp.net identity storage.
I follow this tutorial and the first steps are done.
https://learn.microsoft.com/en-us/aspnet/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider
Now i have the follow mysql command:
"Select Roles.Name from UserRoles, Roles where UserRoles.UserId = #userId and UserRoles.RoleId = Roles.Id"
My problem is now that i dont know how the table have to look for this request?
I would say:
Tablename : Roles
Select: Roles and Name? or is it a name?
same with UserRoles.UserID and UserRoles.RoleId
What does the point mean?
Thanks a lot
You question is quite unclear, however, if I understood correctly, you can't figure out clearly how the database schema you are using is structured and what you'll get from this query.
The query you have written SELECTs the data field called Name from the table called Roles. In order to do this, the query uses data coming from two tables: one is the Roles table itself, the other is called UserRoles.
It will extract Names data from the Roles table only for the Roles entries that have the Id field matching with the RoleId field of the entries in the UserRoles table that have the UserId equal to the given #UserId.
In other words, this SELECT query in will give you as a result a list of Names coming from the entries in the Roles table which match the given conditional check, which is what is written after the where SQL condition: where UserRoles.UserId = #userId and UserRoles.RoleId = Roles.Id.
Finally, the point "." in SQL queries is used to disambiguate between fields (or columns, if you want to call it so) with same name but coming from different tables. It is quite common that all the tables have an Id field, for example. You can identify the correct Id field in your database by writing Table1.Id, Table2.Id, and so on. Even if you don't have naming conflicts in your tables columns, adding the table name can be very good for code readability.
Edit:
As other users correctly pointed out in the comments to your question, you should also have a look to what an SQL JOIN operation is. Since you are searching data using information coming from different tables, you are actually doing an implicit JOIN on those tables.

Read-only after inner join (MySQL)

In MySQL workbench (Mac OS), I wanted to join two tables so that I can update the second one. The code I put in was as follows
select f.company, f.remarks, c.pic
from feedback f, customers c
where f.col = c.col
order by f.company;
The output is a read only table, which prevented me from updating table "customers" based on the f.remarks column.
Your advice/suggestion is appreciated. Thank you.
By hovering above the "Read Only" icon, I got the following message:
"Statement must be a SELECT from a single table with a primary key for its results to be editable".
After some research based on the advice given by fellow coders, here are some points to note:
In MySQL workbench, one cannot edit the results obtained from any JOINs because it's not from a single table;
In using SELECT from a single table, the primary key must be included in order for the result to be editable.
Thank you to everyone who contributed to the question. I appreciate it.
The problem is because, as you mentioned, SELECT only returns a "read only" result set.
So basically you cant use MySQL workbench to update a field in a read only result set that is returned when using a JOIN statement.
from what i understand you want to update table "customers" based on a query.
maybe this post will help you:
update table based on subquery of table

Set two values in one table based on sum of a column in another table

I have two tables, a "data" table with hundreds of thousands of rows, and a "settings" table with hundreds of rows. I need to update two values in the settings table, based on the sum of one column in the data table being greater than another column in the settings table, where the 'id' of the settings table matches the 'offerid' of the data table.
I've been cruising Google looking at many possible solutions, but I don't seem able to bend any of them to my needs. Any time I start working with Joins, I inevitably get tripped up.
My latest attempt which did not work, is:
UPDATE settings a, data b
SET a.hidden=1, a.weight=0
WHERE a.id = b.offerid
AND sum(b.views) > a.target
I liked this flavor of approach as I thought it actually made sense to me, but all I get is "Error code 1111: Invalid us of group function". Maybe someone here can point me in the right direction.
It errors out because you are using an aggregate function (sum) with no grouping. So query really does not know which rows should be summed together. You can use a subquery like this:
UPDATE settings a
INNER JOIN
(
SELECT
sum(b.views) sumviews, b.offerid
from data b
group by b.offerid
) c on c.offerid = a.id
SET a.hidden=1, a.weight=0
where c.sumviews>a.target
EDIT: To disable the safe update function do the following steps
Follow the steps below before executing the UPDATE command:
Go to Edit --> Preferences
Click "SQL Queries" tab and uncheck "Safe Updates" check box
Query --> Reconnect to Server
Now execute your sql query
Source: Disable Safe Update
Try using
HAVING
instead of
AND
So your code goes like:
UPDATE settings a, data b
SET a.hidden=1, a.weight=0
WHERE a.id = b.offerid
GROUP BY a.id
HAVING sum(b.views) > a.target

Delete sql rows with multiple values within where IDs do not have a match in another table

I have two table:
Table: Options
Options
Id xItems
- ItemA,ItemB,ItemC,etc
Table: Items
Items
Id
-
I am attempting to delete all Items rows that are not listed within Options.xitems
I attempted to execute the SQL statement
DELETE FROM items
Where items.id NOT IN (SELECT xitems FROM options)
However the problem is that multiple values are contained within XItems and I only managed to delete rows where Item.Id was the first or only value.
Would appreciate any kind help
EDIT: The following update added from the OP's post as an Answer.
The server is MySQL(tags edited accordingly) which allows one to enter an SQL statement below to execute against any database table or tables. I am a front end dev and get confused with this stuff.
John, I ran the code you posted. Here is the acutal code I applying against backedup test tables
DELETE FROM xbak514q_ecom_prodoptionsel
WHERE NOT FIND_IN_SET(xbak514q_ecom_prodoptionsel.id, (SELECT xprodoptionsel FROM xbak514q_ecom_prodoptions))
which returned the following error:
A problem was encountered while executing the SQL statement submitted.
The error was reported as: The MySQL extension encountered a problem
submitting an SQL statement. MySQL reported the error as: Subquery
returns more than 1 row
This database was configured by a software company who set up an e-comm site. The Items, Product options and selection items(add ons) are quite extensive. Should I consider reformatting the tables?
Again thanks for your kind help
have you tried using find_in_set()??
DELETE FROM items
WHERE NOT FIND_IN_SET(items.id, (SELECT xitems FROM options))
FIDDLE DEMO
NOTE:
find_in_set() is only for MySQL but since you have it tagged for both this may or may not be the solution. however the function looks for a comma separated list that is a single string or item and takes the first argument as the search string
RECOMMENDATION.
you should NEVER store data in the database as a comma separated list like that.. it causes HUGE issues in the future. please consider normalizing your database. if you want a way to do that just post a comment and I'll write up a query that will normalize it for you.

Removing duplicate email address based on the lowest id in mysql

I have a table called emaildata consisting of 4 columns emailaddress, domainname, data and id.
The emailaddress column should contain only unique entries, but there are many duplicates. The domainname and data column are not unique, and as such will contain duplicates which is fine. The id column is set to autoincrement so will contain only unique values.
My question is how do I get rid of all rows that feature duplicate email addresses, keeping the one with the lowest id?
There should be around 370,000 rows, but currently I've got 906,000.
I had an SQL statement before which I used for a similar table and I've tried to adapt it to this without success.
delete T1
from emaildata T1, emaildata T2
where T1.emailaddress = T2.emailaddress
and T1.id > T2.id
The above was based upon the following which was applied to another table and worked fine.
delete T1
from email_list_subscribers T1, email_list_subscribers T2
where T1.emailaddress = T2.emailaddress
and T1.subscriberid > T2.subscriberid
I've tried running this against my table on the remote server in phpmyadmin and after pressing the GO button, the loading bar comes up in the middle, then disappears as if it is processing - but it never does.
I've tried repeating this against the same table running on my home server (XAMPP) via phpmyadmin, and again with HeidiSQL - the same problem with phpmyadmin and Heidi appears to crash.
I've tried other soloutions that i've seen on here but I seem to be getting the same "timeout" / crash problem. I never had issues with the original statement running on the remote server, granted this was against a database a third of the size.
Any info would be appreciated.
Your query appears to be correct. Your issue seems to be a performance issue, not a logic issue. You'll need to make sure that both your emailaddress and id fields are properly indexed in the database - otherwise with close to a million rows, I would expect your query to hang.
(I would guess that id is probably already indexed, but not emailaddress. Especially with doing a join between tables, if either one of these fields is not indexed, you're going to be looking at a LOT of full table scans.)
Edit:
Seeing your comment that this is the case, you can follow the documentation at http://dev.mysql.com/doc/refman/5.0/en/create-index.html for creating indices. So something like:
CREATE INDEX email_index ON emaildata(emailaddress) USING BTREE;
Never tryed to see if array_unique (php function) ever modifies the key but here is how u can do...
select id and email and store them in an array like id => email
after use array_unique to get a new array with the first id for each repetiteve group...thats how function works... and after comapre the 2 arrays and delete the remaining ids from ur table...
this way u get the first id from repetitive groups and unique values