Updating data using a SELECT query (with two related tables) - mysql

I have been trying to update the data behind a SELECT query, but not getting too far, so I have created a new database, with the hope of finding a solution.
I have two tables:
table_a and table_b
table_a:
ID, item_to_match, new_value *(this is initially blank)*
table_b:
IDB, item_to_match, new_value *(the value I want to get into table_a)*
Somehow, I want to update new_value in table_a with new_value from table_b - but I can't seem to get it (I am new to this).
I tried creating an UPDATE query, but that only allowed me to show one of the two tables. So I tried creating a master query (called main), thinking I could create an UPDATE query on that - but I can't get that to work either. Here is the syntax:
SELECT
`table_a`.`new_value` AS `goingto`,
`table_b`.`new_value` AS `takenfrom`
FROM (`table_a`
JOIN `table_b`
ON ((`table_a`.`item_to_match` = `table_b`.`item_to_match`)))
I really, really would appreciate a bit more guidance on how to do this (sorry to keep asking).
I have now tried three variations and keep getting the same error message. But here are the variations:
UPDATE table_a, table_b
SET table_a.new_value = table_b.new_value
WHERE table_a.item_to_match = table_b.item_to_match
UPDATE table_a a
INNER JOIN table_b b ON a.item_to_match = b.item_to_match
SET a.new_value = b.new_value
UPDATE table_a a,table_b b
SET a.new_value = b.new_value
WHERE a.item_to_match = b.item_to_match
The field item_to_match is not a primary key or indexed (FYI)...
What the heck am I doing wrong???
I also just tried:
UPDATE table_a a
JOIN table_b b
ON a.item_to_match = b.item_to_match
SET a.new_value = b.new_value
Is the syntax right....am I doing something wrong in the app itself?

Here is how you can do it
UPDATE table_a AS a
INNER JOIN table_b AS b ON a.item_to_match = b.item_to_match
SET a.new_value = b.new_value

You don't need to say which table(s) you're updating, that's implicit in your SET clause.
UPDATE tableA a
JOIN tableB b
ON a.a_id = b.a_id
JOIN tableC c
ON b.b_id = c.b_id
SET b.val = a.val+c.val
WHERE a.val > 10
AND c.val > 10;
There is no FROM clause.
Please refer this question asked in SO.

Related

MySQL - update values in table returned from query?

I fired this query where I join two tables and output some of the columns of both tables:
SELECT B.option_id, B.product_id, A.title, B.identifier
FROM `catalog_product_option_title` A JOIN
`catalog_product_option` B
ON A.option_id = B.option_id
WHERE A.title = "Breite"
Result:
Now I need to enter the example value xyz on the column identifier in the result, everywhere. I would go ahead and do this by hand.
How can I make use of the update statement from MySQL to solve this without having to manually change it by hand?
I tried it like this:
UPDATE `catalog_product_option`
SET identifier = 'xyz'
WHERE option_id IN (
SELECT A.option_id
FROM `catalog_product_option_title` A
JOIN
`catalog_product_option` B
ON A.option_id = B.option_id
WHERE A.title = "Breite"
)
But the simulation of this query returned that this would change 0 lines.
UPDATE
I called the sql without simulating it, and now I get this error:
1093 - Table 'catalog_product_option' is specified twice, both as a target for 'UPDATE' and as a separate source for data
You could rewrite your query as a JOIN:
UPDATE `catalog_product_option` B
JOIN `catalog_product_option_title` A ON A.option_id = B.option_id
SET B.identifier = 'xyz' WHERE A.title = "Breite"
Can you try like this please?
UPDATE `catalog_product_option`
SET identifier = 'xyz'
WHERE option_id IN (
SELECT option_id FROM (SELECT A.option_id
FROM `catalog_product_option_title` A
JOIN
`catalog_product_option` B
ON A.option_id = B.option_id
WHERE A.title = "Breite") as x
)

mysql update from another table

I want to update the MySQL table cp5sql from table spanish and am using the following statement in PhpMyadmin. The field names are correct, although a little different in each table. The last part of the statement is limiting the update to word 'able' just for testing.
I get an error that something is wrong on line 2.
UPDATE cp5sql c
SET (Spanish_ID, Spanish_Type,Spanish_Uoffset,Spanish_Synset,Spanish_Word)=
(SELECT SID,type,offset,synset,word FROM spanish s
WHERE s.type=c.Type AND s.synset=c.synset AND c.Word ='able');
I have also tried:
UPDATE cp5sql
SET (Spanish_ID, Spanish_Type,Spanish_Uoffset,Spanish_Synset,Spanish_Word)=
(SELECT SID,type,offset,synset,word FROM spanish
WHERE spanish.type=cp5sql.Type AND spanish.synset=cp5sql.synset AND cp5sql.Word ='able');
You have a good guess, but it's actually an UPDATE FROM syntax.
Something like this:
UPDATE
Table_A
SET
Table_A.col1 = Table_B.col1,
Table_A.col2 = Table_B.col2
FROM
Some_Table AS Table_A
INNER JOIN Other_Table AS Table_B
ON Table_A.id = Table_B.id
WHERE
Table_A.col3 = 'cool'
Trying to make your example into this syntax would be something like:
UPDATE cp5sql c
SET Spanish_ID = SID,
Spanish_Type = type,
Spanish_Uoffset = offset,
Spanish_Synset = synset,
Spanish_Word = word
FROM spanish s
WHERE s.type = c.Type
AND s.synset = c.synset
AND c.Word ='able';
You have to use UPDATE JOIN:
UPDATE cp5sql c
JOIN spanish s
ON s.type = c.Type AND s.synset = c.synset AND c.Word = 'able'
SET
c.Spanish_ID = s.SID,
c.Spanish_Type = s.type,
c.Spanish_Uoffset = s.offset,
c.Spanish_Synset = s.synset,
c.Spanish_Word = s.word;

MariaDB update error inner join and select

I hope you can help me again, thanks already for pointing me to the right direction with creating the check digit for the new IBAN in Germany. I am now trying to update our membership database with the newly calculated BIC and IBAN but seem to have a problem with the UPDATE statement on the MariaDB MySQL database, despite the fact that I think I got the syntax right.
All I am trying to do is set the two fields "konto_bic" and "konto_iban" in the table "mitglieder" from the SELECT statement which creates a temporary table called b with the columns "id", "bic" and "iban". The "id" is the same in the two tables.
Here is my first try:
update a
set a.`konto_bic` = b.`BIC`, a.`konto_iban` = b.`IBAN`
from `mitglieder` a
INNER JOIN (SELECT m.`id`, m.`nachname`, m.`vorname`, m.`konto_bank`, m.`konto_blz`, m.`konto_nummer`, k.`bic` AS 'BIC', CONCAT('DE',LPAD(98-MOD(CONVERT(CONCAT(m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0'),'1314','00'), decimal(24)),97),2,'0'),m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0')) AS 'IBAN'
FROM `mitglieder` m
LEFT JOIN `konvert_bic_blz` k
ON m.`konto_blz` = k.`blz`
ORDER BY m.`nachname`, m.`vorname`) b
ON a.`id` = b.`id`
However, this produced an error and I tried this instead:
update `mitglieder` a
set a.`konto_bic` = b.`bic`, a.`konto_iban` = b.`iban`
FROM (SELECT m.`id` as 'id', k.`bic` as 'bic', CONCAT('DE',LPAD(98-MOD(CONVERT(CONCAT(m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0'),'1314','00'), decimal(24)),97),2,'0'),m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0')) AS 'iban'
FROM `mitglieder` m
LEFT JOIN `konvert_bic_blz` k
ON m.`konto_blz` = k.`blz`) b
WHERE a.`id` = b.`id`
That also did not get me any further (error from DB).
Can anyone see what my syntax error might be?
Thank you in advance for your help
Stephan
Try below SQL
UPDATE `mitglieder` a,
(SELECT m.`id` AS 'id',
k.`bic` AS 'bic',
CONCAT('DE',LPAD(98-MOD(CONVERT(CONCAT(m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0'),'1314','00'), decimal(24)),97),2,'0'),m.`konto_blz`,LPAD(m.`konto_nummer`,10,'0')) AS 'iban'
FROM `mitglieder` m
LEFT JOIN `konvert_bic_blz` k ON m.`konto_blz` = k.`blz`) b
SET a.`konto_bic` = b.`bic`, a.`konto_iban` = b.`iban`
WHERE a.`id` = b.`id`
UPDATE Syntax
http://dev.mysql.com/doc/refman/5.0/en/update.html
I tried this on MariaDB 10.2.6 :
SET sql_mode = 'ANSI_QUOTES'
UPDATE "test"."user" AS "a"
INNER JOIN "test"."user_profile" AS "c" ON "c".user_id = "a".id
INNER JOIN "test"."profile" AS "d" ON "d".id = "c".profile_id
SET "a".firstname = 'laurent'
WHERE "a".id = 3;
And it works :)

How to update table records with another table

I have a problem with updating records in my table. I am doing research all day but it is just beyond me.
Basics: I have two tables
TABLE1
TABLE2
I need to update nr_g from TABLE1 with id from TABLE2 but only where 'kraj' 'region' 'nazwa_hotelu' from TABLE1 is equal 'country' 'region' 'hotelName' from TABLE2
my trying so far:
UPDATE merlinx u
LEFT JOIN
merlinx_new s ON u.nr_g != s.id
SET
u.nr_g = s.id
WHERE
u.kraj = s.country AND u.nazwa_hotelu = s.hotelName AND u.region = s.region
That is updating me only 4 rows... and 1592 are unsafe statements
another shot of mine:
UPDATE merlinx_merged
SET
nr_g = (SELECT
merlinx_new.id
FROM
merlinx_new
INNER JOIN
merlinx_merged
WHERE
merlinx_new.country = merlinx_merged.kraj
AND merlinx_new.hotelName = merlinx_merged.nazwa_hotelu
AND merlinx_new.region = merlinx_merged.region)
And that is just throwing errors.
My mind is fried after 8 hours wasted on it. Help is much appreciated.
I think your issue is in your join statement. You have
LEFT JOIN merlinx_new s ON u.nr_g != s.id
You shouldn't have to have the ON criteria in that (if I'm understanding your question correctly).
This should do the trick if you want to overwrite merlinx.nr_g with the value from merlinx_new.id if all of your criteria matches in the WHERE clause.
UPDATE merlinx u, merlinx_new s
SET u.nr_g = s.id
WHERE u.kraj = s.country AND u.nazwa_hotelu = s.hotelName AND u.region = s.region

MySQL - UPDATE query based on SELECT Query

I need to check (from the same table) if there is an association between two events based on date-time.
One set of data will contain the ending date-time of certain events and the other set of data will contain the starting date-time for other events.
If the first event completes before the second event then I would like to link them up.
What I have so far is:
SELECT name as name_A, date-time as end_DTS, id as id_A
FROM tableA WHERE criteria = 1
SELECT name as name_B, date-time as start_DTS, id as id_B
FROM tableA WHERE criteria = 2
Then I join them:
SELECT name_A, name_B, id_A, id_B,
if(start_DTS > end_DTS,'VALID','') as validation_check
FROM tableA
LEFT JOIN tableB ON name_A = name_B
Can I then, based on my validation_check field, run a UPDATE query with the SELECT nested?
You can actually do this one of two ways:
MySQL update join syntax:
UPDATE tableA a
INNER JOIN tableB b ON a.name_a = b.name_b
SET validation_check = if(start_dts > end_dts, 'VALID', '')
-- where clause can go here
ANSI SQL syntax:
UPDATE tableA SET validation_check =
(SELECT if(start_DTS > end_DTS, 'VALID', '') AS validation_check
FROM tableA
INNER JOIN tableB ON name_A = name_B
WHERE id_A = tableA.id_A)
Pick whichever one seems most natural to you.
UPDATE
`table1` AS `dest`,
(
SELECT
*
FROM
`table2`
WHERE
`id` = x
) AS `src`
SET
`dest`.`col1` = `src`.`col1`
WHERE
`dest`.`id` = x
;
Hope this works for you.
Easy in MySQL:
UPDATE users AS U1, users AS U2
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id
If somebody is seeking to update data from one database to another no matter which table they are targeting, there must be some criteria to do it.
This one is better and clean for all levels:
UPDATE dbname1.content targetTable
LEFT JOIN dbname2.someothertable sourceTable ON
targetTable.compare_field= sourceTable.compare_field
SET
targetTable.col1 = sourceTable.cola,
targetTable.col2 = sourceTable.colb,
targetTable.col3 = sourceTable.colc,
targetTable.col4 = sourceTable.cold
Traaa! It works great!
With the above understanding, you can modify the set fields and "on" criteria to do your work. You can also perform the checks, then pull the data into the temp table(s) and then run the update using the above syntax replacing your table and column names.
Hope it works, if not let me know. I will write an exact query for you.
UPDATE
receipt_invoices dest,
(
SELECT
`receipt_id`,
CAST((net * 100) / 112 AS DECIMAL (11, 2)) witoutvat
FROM
receipt
WHERE CAST((net * 100) / 112 AS DECIMAL (11, 2)) != total
AND vat_percentage = 12
) src
SET
dest.price = src.witoutvat,
dest.amount = src.witoutvat
WHERE col_tobefixed = 1
AND dest.`receipt_id` = src.receipt_id ;
Hope this will help you in a case where you have to match and update between two tables.
I found this question in looking for my own solution to a very complex join. This is an alternative solution, to a more complex version of the problem, which I thought might be useful.
I needed to populate the product_id field in the activities table, where activities are numbered in a unit, and units are numbered in a level (identified using a string ??N), such that one can identify activities using an SKU ie L1U1A1. Those SKUs are then stored in a different table.
I identified the following to get a list of activity_id vs product_id:-
SELECT a.activity_id, w.product_id
FROM activities a
JOIN units USING(unit_id)
JOIN product_types USING(product_type_id)
JOIN web_products w
ON sku=CONCAT('L',SUBSTR(product_type_code,3), 'U',unit_index, 'A',activity_index)
I found that that was too complex to incorporate into a SELECT within mysql, so I created a temporary table, and joined that with the update statement:-
CREATE TEMPORARY TABLE activity_product_ids AS (<the above select statement>);
UPDATE activities a
JOIN activity_product_ids b
ON a.activity_id=b.activity_id
SET a.product_id=b.product_id;
I hope someone finds this useful
UPDATE [table_name] AS T1,
(SELECT [column_name]
FROM [table_name]
WHERE [column_name] = [value]) AS T2
SET T1.[column_name]=T2.[column_name] + 1
WHERE T1.[column_name] = [value];
You can update values from another table using inner join like this
UPDATE [table1_name] AS t1 INNER JOIN [table2_name] AS t2 ON t1.column1_name] = t2.[column1_name] SET t1.[column2_name] = t2.column2_name];
Follow here to know how to use this query http://www.voidtricks.com/mysql-inner-join-update/
or you can use select as subquery to do this
UPDATE [table_name] SET [column_name] = (SELECT [column_name] FROM [table_name] WHERE [column_name] = [value]) WHERE [column_name] = [value];
query explained in details here http://www.voidtricks.com/mysql-update-from-select/
You can use:
UPDATE Station AS st1, StationOld AS st2
SET st1.already_used = 1
WHERE st1.code = st2.code
For same table,
UPDATE PHA_BILL_SEGMENT AS PHA,
(SELECT BILL_ID, COUNT(REGISTRATION_NUMBER) AS REG
FROM PHA_BILL_SEGMENT
GROUP BY REGISTRATION_NUMBER, BILL_DATE, BILL_AMOUNT
HAVING REG > 1) T
SET PHA.BILL_DATE = PHA.BILL_DATE + 2
WHERE PHA.BILL_ID = T.BILL_ID;
I had an issue with duplicate entries in one table itself. Below is the approaches were working for me. It has also been advocated by #sibaz.
Finally I solved it using the below queries:
The select query is saved in a temp table
IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') IS NOT NULL
DROP TABLE #New_format_donor_temp;
select *
into #New_format_donor_temp
from DONOR_EMPLOYMENTS
where DONOR_ID IN (
1, 2
)
-- Test New_format_donor_temp
-- SELECT *
-- FROM #New_format_donor_temp;
The temp table is joined in the update query.
UPDATE de
SET STATUS_CD=de_new.STATUS_CD, STATUS_REASON_CD=de_new.STATUS_REASON_CD, TYPE_CD=de_new.TYPE_CD
FROM DONOR_EMPLOYMENTS AS de
INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO
WHERE
de.DONOR_ID IN (
3, 4
)
I not very experienced with SQL please advise any better approach you know.
Above queries are for MySql server.
if you are updating from a complex query. The best thing is create temporary table from the query, then use the temporary table to update as one query.
DROP TABLE IF EXISTS cash_sales_sums;
CREATE TEMPORARY TABLE cash_sales_sums as
SELECT tbl_cash_sales_documents.batch_key, COUNT(DISTINCT tbl_cash_sales_documents.cash_sale_number) no_of_docs,
SUM(tbl_cash_sales_documents.paid_amount) paid_amount, SUM(A.amount - tbl_cash_sales_documents.bonus_amount - tbl_cash_sales_documents.discount_given) amount,
SUM(A.recs) no_of_entries FROM
tbl_cash_sales_documents
RIGHT JOIN(
SELECT
SUM(
tbl_cash_sales_transactions.amount
)amount,
tbl_cash_sales_transactions.cash_sale_document_id,
COUNT(transaction_id)recs
FROM
tbl_cash_sales_transactions
GROUP BY
tbl_cash_sales_transactions.cash_sale_document_id
)A ON A.cash_sale_document_id = tbl_cash_sales_documents.cash_sale_id
GROUP BY
tbl_cash_sales_documents.batch_key
ORDER BY batch_key;
UPDATE tbl_cash_sales_batches SET control_totals = (SELECT amount FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key LIMIT 1),
expected_number_of_documents = (SELECT no_of_docs FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key),
computer_number_of_documents = expected_number_of_documents, computer_total_amount = control_totals
WHERE batch_key IN (SELECT batch_key FROM cash_sales_sums);
INSERT INTO all_table
SELECT Orders.OrderID,
Orders.CustomerID,
Orders.Amount,
Orders.ProductID,
Orders.Date,
Customer.CustomerName,
Customer.Address
FROM Orders
JOIN Customer ON Orders.CustomerID=Customer.CustomerID
WHERE Orders.OrderID not in (SELECT OrderID FROM all_table)