Updating one table by selecting another table with identical structure - mysql

Well I m pretty stuck in this problem, I have two tables with identical structure, I want to update first table with values of 2nd table. I have following query but mysql is throwing the error.
UPDATE property p
SET ROW = (SELECT * FROM temp_property t WHERE p.id= t.id)
Can anybody shed some light on this?

I'm pretty sure you can't update an entire row all at once. You need to specify the column names.
UPDATE property p, temp_property t
SET p.col1 = t.col1, etc
WHERE p.id=tp.id
(Fixed query for MySQL.)

Related

Append records from one table to another using the common field

There are many varied posts about this matter, but I am unable to find the answer I need. I am hoping this question is unique.
I am trying to append all the data from one table to another, without creating new records. The data in the second table is really a subset of data for a portion of the existing records in the first table.
For example:
I have the table "SPK". And I want to write all of the data from SPK into the table "RCT". The common field between each record I want to match is the RegID, which is unique in both tables (i.e. there is only one SPK record per RCT record).
If I understand correctly, you mean append the columns in one table (call it SECOND) to the other (call it FIRST).
In that case, does this work ?
UPDATE
regcontactsTest
JOIN
speakersTest
ON speakersTest.RegistrationID = regcontactsTest.RegistrationID
SET regcontactsTest.presentationtitle = speakersTest.presentationtitle
EDIT: Updated the query based on Mariadb syntax
You need to use JOIN. For general Update join :
update tab1 a
join tab2 b ON a.join_colA = b.join_colB
SET a.columnToUpdate = [something]
Or in other words:
update
tab1 a
join tab2 b on ..
set a.field=...;

Create a new table from multiple tables with identical column names without declaring the column names

I have 3 tables that I'd like to pull data from and use the result set to create a new table. Note that each of these tables have identical column names.
CREATE TABLE smsout_32020Nov2014
AS
(SELECT *
FROM smsout17nov2014b,smsoutnov32014,smsout
WHERE smsoutnov32014.shortcode = 32020
AND smsout.shortcode = 32020
AND smsout17nov2014b.shortcode = 32020);
Problem is that I am getting an error that there are duplicate column names
Is there a work around?
As described in comments on your question, it is unclear what results you are actually trying to obtain. Supposing that the question reflects a complete misunderstanding of join operations, however, it may be that UNION ALL is what you're actually looking for. In particular, if you want all the rows of the three named tables for which the shortcode column has the value 32020, then that would be this:
CREATE TABLE smsout_32020Nov2014 AS (
SELECT smsout17nov2014b.*
WHERE shortcode = 32030
UNION ALL
SELECT smsoutnov32014.*
WHERE shortcode = 32030
UNION ALL
SELECT smsout.*
WHERE shortcode = 32030
)
On the other hand, if the results you are selecting are in fact in the form you want, as you have revised your question to say, then you have no alternative but to assign explicit column names to ensure column name uniqueness (so at least for every column in two of the three base tables). You can do this via aliases in the SELECT statement or via a column list in the outer CREATE TABLE statement (or both). Your original question seemed to say that the workaround you wanted was a way to avoid doing that, but now it just seems to say that you want to fix the error.
It will be a bit simpler to do the patch up in the SELECT statement. Based on your revised starting query, that would be something like this:
CREATE TABLE smsout_32020Nov2014 AS (
SELECT
smsout.*,
m.col1 AS month_col1, m.col2 AS month_col2, ... m.shortcode AS month_shortcode,
c.col1 AS code_col1, c.col2 AS code_col2, ... c.shortcode AS code_shortcode,
FROM
smsout17nov2014b m,
smsoutnov32014 c,
smsout
WHERE smsoutnov32014.shortcode = 32020
AND smsout.shortcode = 32020
AND smsout17nov2014b.shortcode = 32020
);
The columns of your new table will be col1, col2, ... shortcode, month_col1, month_col2, ... month_shortcode, code_col1, code_col2, ... code_shortcode.
Note, by the way, that even if those results are in the form you want (which I find surprising), I have trouble believing that the rows are what you want.

how to update many rows at same time using my sql

I got one table called family, which contains a column called power. I want to update maximum ten values of power by adding one in each row and the rest remains the same. I try my own method by creating another table which contains the maximum ten values that I want to update and create a query below, but got some problems. Here's the query:
UPDATE family
SET family.total = (SELECT totalmax.total FROM totalmax
INNER JOIN familyone
ON family.family_id2 = totalmax.family_id2
WHERE family.family_id2 = totalmax.family_id2)
Can someone tell me where's the problem with this query and is there any other methods to solve my problem?
You could do this with a join
UPDATE family
INNER JOIN
totalmax
ON family.family_id2 = totalmax.family_id2
SET family.total = totalmax.total

Find matches from 2 tables, change other field?

I have a database with two separate tables. One table (T1) has 400+ values in its only column, while the other (T2) has 14,000+ rows and multiple columns.
What I need to do is to compare the column in T1 to one column in T2. For every matching value, I need to update a different value in the same row in T2.
I know this is pretty easy and straight-forward, but I'm new to MySQL and trying to get this down before I go back to other things. Thanks a ton in advance!
EDIT: Here's what I've been trying to no avail..
UPDATE `apollo`.`Source`, `apollo`.`Bottom`
SET `Source`.`CaptureInterval` = '12'
WHERE `Bottom`.`URL` LIKE `Source`.`SourceID`
EDIT 2:
A little clarification:
apollo.Bottom and apollo.Source are the two tables.
apollo.Bottom is the table with one column and 400 records in that column.
I want to compare Bottom.URL to Source.SourceID. If they match, I want to update Source.CaptureInterval to 12.
You can use the following query to update. But the performance will be much better if you index URL and SourceID columns in both tables as they are being used in the WHERE clause.
UPDATE `apollo`.`Source`, `apollo`.`Bottom`
SET `Source`.`CaptureInterval` = '12'
WHERE `Bottom`.`URL` = `Source`.`SourceID`
You can join the two tables together and do a multiple table update.
Start with something like this:
UPDATE `apollo`.`Source`
INNER JOIN `apollo`.`Bottom` ON `apollo`.`Bottom`.`URL` = `apollo`.`Source`.`SourceID`
SET `apollo`.`Source`.`CaptureInterval` = '12';

Copy data from table to another table MySQL

I'm having a problem updating newly added records that don't have a timestamp to another identical table in the same database. Here is my query
INSERT INTO mlscopy
SELECT * FROM mls_cvrmls AS parent
LEFT JOIN mlscopy AS child
ON child.listing_listnum != parent.listing_listnum
The parent table is updated by a separate company every morning, and unfortunately there are no timestamps(datetime) to relate the newly added records.
My child table(the copy) is needed for google geocoding since their morning udpates drop and create the parent table each morning.
I made a structure and data copy of the parent table, then deleted the last ten records to test my query. But I keep receiving the error Column count doesn't match value count at row 1.
Can't think of what I'm doing wrong here.
Here are the column table names
listing_listing
listing_listnum
listing_propertytype
listing_status
listing_listingpublicid
listing_agentname
listing_agentlist
listing_listingbrokercode
listing_officelist
listing_lo
listing_lo00
listing_lo01
listing_lo02
listing_lo03
listing_lo04
listing_lo05
listing_agentcolist
listing_agentcolist00
listing_officecolist
listing_area
listing_listdate
listing_listprice
listing_streetnumdisplay
listing_streetdirectional
listing_streetname
listing_streettype
listing_countyid
listing_zipcode
listing_zipplus4
listing_postoffice
listing_subdivision
listing_neighborhood
listing_schoolelem
listing_schooljunior
listing_schoolhigh
listing_pud
listing_lotdim
listing_acres
listing_zoning
listing_sqfttotal
listing_sqftunfinished
listing_rooms
listing_bedrooms
listing_stories
listing_basement
listing_garage
listing_garagecap
listing_fireplaces
listing_pool
listing_bathsfull
listing_bathshalf
listing_bathstotal
listing_bathsfullbsmt
listing_bathsfulllevel1
listing_bathsfulllevel2
listing_bathsfulllevel3
listing_bathshalfbsmt
listing_bathshalflevel1
listing_bathshalflevel2
listing_bathshalflevel3
listing_roombed2desc
listing_roombed2length
listing_roombed2level
listing_roombed2width
listing_roombed3desc
listing_roombed3length
listing_roombed3level
listing_roombed3width
listing_roombed4desc
listing_roombed4length
listing_roombed4level
listing_roombed4width
listing_roombed5desc
listing_roombed5length
listing_roombed5level
listing_roombed5width
listing_roomdiningdesc
listing_roomdininglength
listing_roomdininglevel
listing_roomdiningwidth
listing_roomfamilydesc
listing_roomfamilylength
listing_roomfamilylevel
listing_roomfamilywidth
listing_roomfloridadesc
listing_roomfloridalength
listing_roomfloridalevel
listing_roomfloridawidth
listing_roomfoyerdesc
listing_roomfoyerlength
listing_roomfoyerlevel
listing_roomfoyerwidth
listing_roomgreatdesc
listing_roomgreatlength
listing_roomgreatlevel
listing_roomgreatwidth
listing_roomkitchendesc
listing_roomkitchenlength
listing_roomkitchenlevel
listing_roomkitchenwidth
listing_roomlaundrydesc
listing_roomlaundrylength
listing_roomlaundrylevel
listing_roomlaundrywidth
listing_roomlivingdesc
listing_roomlivinglength
listing_roomlivinglevel
listing_roomlivingwidth
listing_roommasterbrdesc
listing_roommasterbrlength
listing_roommasterbrlevel
listing_roommasterbrwidth
listing_roomofficedesc
listing_roomofficelength
listing_roomofficelevel
listing_roomofficewidth
listing_roomother1desc
listing_roomother1length
listing_roomother1level
listing_roomother1width
listing_roomother1
listing_roomother2desc
listing_roomother2length
listing_roomother2level
listing_roomother2width
listing_roomother2
listing_roomrecdesc
listing_roomreclength
listing_roomreclevel
listing_roomrecwidth
listing_handicap
listing_yearbuilt
listing_lotdesc
listing_construction
listing_watertype
listing_roof
listing_attic
listing_style
listing_floors
listing_fireplacedesc
listing_structure
listing_walltype
listing_basedesc
listing_appliances
listing_interior
listing_exterior
listing_amenities
listing_pooldesc
listing_fence
listing_porch
listing_heatsrc
listing_heatsystem
listing_coolsystem
listing_waterheater
listing_watersewer
listing_parking
listing_garagedesc
listing_handicapdesc
listing_feedesc
listing_restrictions
listing_terms
listing_assocfeeincludes
listing_building
listing_possession
listing_farmtype
listing_ownerdesc
listing_irrigationsrc
listing_taxyear
listing_taxamount
listing_directions
listing_remarks
listing_virtualtourlink
listing_vowavmyn
listing_vowcommyn
listing_addressdisplayyn
listing_f174
listing_proptype
listing_lat
listing_lon
listing_photo1
listing_listofficename
listing_vtoururl
listing_multiphotoflag
id <- primary key
If you only run the SELECT statement from your INSERT you will see that your select returns all the columns of both mls_cvrmls AND mlscopy.
You probably need:
INSERT INTO mlscopy
SELECT parent.* FROM mls_cvrmls AS parent
LEFT JOIN mlscopy AS child
ON child.listing_listnum != parent.listing_listnum
EDIT
I am not sure your JOIN condition is correct. This kind of condition will probably return many records you did not wish for. Each record in mls_cvrmls has many (many!) records in mlscopy which satisfy the condition.
As an example, let's assume the 2 tables have 3 columns, and you want to add all records from parent to child, as long as they don't exists there anymore.
INSERT INTO mlscopy (listing_listing, listing_listnum, listing_propertytype)
SELECT parent.listing_listing,
parent.listing_listnum,
parent.listing_propertytype // (more columns...)
FROM mls_cvrmls AS parent
LEFT JOIN mlscopy AS child
ON child.listing_listnum = parent.listing_listnum
WHERE child.listing_listnum IS NULL
Couple of things here.
The error message is because "select *" gives you all columns from all tables in the query. That is, each row has all the columns from mls_cvrmls PLUS all the columns from mlscopy. This is not going to be suitable for inserting into mlscopy because it's going to have many extra columns. If the two tables have all the same columns, then they will all be doubled.
Your WHERE clause is unlikely to be correct. This is saying that for every row in parent, you want all the rows in child that don't match. Think this through. Suppose parent has listing_listnum values of 1, 2, and 4, and child has value 1, 4, and 5. So the pairs 1/1 and 4/4 will be excluded. But you'll get the pairs 1/4, 1/5, 2/4, 2/5, 4/1, and 4/5. I think what you really want here is to just get the records from parent that aren't found on child at all, like in this example, just 2. So what you probably really want is a "not exists" query.
I'm not entirely clear from your description, but you say you want to "update newly added records", but then you do an INSERT. Do you want to update existing records, or do you want to insert new records?
So assuming that what you want to do is find records that are in mls_cvrmls but not in mlscopy and insert these records, I think the correct query would be more like -- and your field list is long so I'll just pick a few sample fields to make the point:
insert into mlscopy (listing_listing, listing_listnum, listing_propertytype, listing_status
listing_listingpublicid, listing_agentname)
select listing_listing, listing_listnum, listing_propertytype, listing_status
listing_listingpublicid, listing_agentname
from mls_cvrmls
where not exists (select 1 from mlscopy where mlscopy.listing_listnum=mls_cvrmls.listing_listnum)
As Icarus says, you should list all columns explicitly. Among the many reasons for this, even if the two tables have all the same fields, if they do not occur in the same order, "insert into mlscopy select *" will not work, because a SQL engine does not match names, it just takes the fields in each table in the order they occur. This may seem like a pain if the list is long, but trust me, after you've been burned a few times by mysterious problems, you'll want to list the fields explicitly.
And just a side note: Why do you prefix all the column names with "listing_" ? This just makes more to type every time you use the table. If you have another table that has names that would otherwise be the same and you need to distinguish, you can always prefix with the table name, like "mls_cvrmls.propertytype".
Get used to list-all-your-columns and you will save yourself some headaches like this and in the future your code won't break if they add more columns.
Change your sql statement to something like this
INSERT INTO mlscopy (col1,col2,col3...coln)
SELECT col1,col2,col3....coln FROM mls_cvrmls AS parent
LEFT JOIN mlscopy AS child
ON child.listing_listnum != parent.listing_listnum
The two tables have different structures, and you're not specifying WHICH fields would be copied across. If you must have different structures, you'll have to explicitly state WHICH fields should be copied. MySQL isn't smart enough to figure that sort of mismatch out on its own, so it complains and aborts.