https://electrictoolbox.com/cross-table-update/
MySQL UPDATE cross table
Cross Table Update with MySQL
Using MySQL version 4.0 or higher you can update a table by joining two or more tables together; note that the examples shown in this article are not possible with MySQL 3.23 or earlier. By joining two tables together you can update one table based on fields in associated records in another table.
Let's say for example you have a product table which stores information about products and a productPrice table which has pricing information and you want to update the prices based on when the product was created (in the examples below you want to discount all your older stuff to 80% of the current price).
In MySQL you can do this in one of two ways. The first is do do a join using commas, like so:
The second way is to use inner join syntax as shown below. This syntax is slightly more flexible as it means you can use left and right joins as well as inner joins, whereas the previous example is an implicit inner join.
Another example of doing this in MySQL but using a left join to flag all the products that do not have associated entries in the productPrice table is as follows:
This isn't necessarily a very realistic example as you would be more likely to want to straight out delete the non-matching entries or use a select query instead to display them in a list for editing but it illustrates how it can be done. The article about how to delete records with MySQL using a cross join uses these examples to delete instead of update.
Note that it's also possible in MySQL to update values in all the tables that are joined in the query. In this example we're doing the same query as in the first two examples but also updating the "dateUpdated" value in the product table.
(CURDATE() is the MySQL function to return the current system date. For other date and time functions in MySQL refer to the MySQL date and time functions manual page).
https://www.mysqltutorial.org/compare-two-tables-to-find-unmatched-records-mysql.aspx/
Compare values of id and title column of both tables:
SELECT id,title
FROM (
SELECT id, title FROM t1
UNION ALL
SELECT id,title FROM t2
) tbl
GROUP BY id, title
HAVING count(*) = 1
ORDER BY id;
Comments
Post a Comment