简体   繁体   中英

Updating all columns of a table from another table's data?

What I want to do is simple but I lack some sql knowledge, so I would truly appreciate any kind of help.

I have table 'dev'.

product1 | product2 | count
---------------------

I also have a table likes.

wishlist_id | user_id | product_id
-------------------------------
1           2        54
2           2        60
3           3        54
7           3        60
..          ..       ..
99          99       99

I want to find how many times 2 products where liked together, but instead of creating a view I want to save the data in the dev table. How can I update the rows so dev table becomes:

         dev
-----------------------
product1 product2 count 
54       60       2
..

EDIT

I don't know how to actually use the update statement here.

my query is :

SELECT i1.product_id as product1, i2.product_id as product2, 
        COUNT(*) as num 
FROM likes i1 
    INNER JOIN likes i2 ON i1.wishlist_id = i2.wishlist_id 
        AND i1.product_id < i2.product_id 
GROUP BY product1, product2;

Suppose your dev table has a unique key constraint on the pair of product1, product2:

CREATE TABLE dev (
  product1 INT NOT NULL,
  product2 INT NOT NULL,
  count INT NOT NULL DEFAULT 0,
  PRIMARY KEY (product1, product2)
);

Now you can use INSERT...ON DUPLICATE KEY UPDATE to add or replace rows corresponding to pairs of your products. You already had a SELECT statement that generated the rows, now you need to use it in an IODKU.

INSERT INTO dev (product1, product2, count)
 SELECT i1.product_id as product1, i2.product_id as product2, COUNT(*) as num 
 FROM likes i1 INNER JOIN likes i2 
   ON i1.wishlist_id = i2.wishlist_id AND i1.product_id < i2.product_id 
 GROUP BY product1, product2
ON DUPLICATE KEY UPDATE count = VALUES(count);

Read more about IODKU here: https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM