[英]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. 我想做的很简单,但是我缺少一些SQL知识,因此,我将不胜感激任何帮助。
I have table 'dev'. 我有表'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. 我想找到2个产品一起喜欢的次数,但是我不想创建视图,而是想将数据保存在dev表中。 How can I update the rows so dev table becomes:
如何更新行,使dev表变为:
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: 假设您的dev表在一对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. 现在,您可以使用INSERT ... ON DUPLICATE KEY UPDATE添加或替换与产品对相对应的行。 You already had a SELECT statement that generated the rows, now you need to use it in an IODKU.
您已经具有生成行的SELECT语句,现在需要在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 在此处阅读有关IODKU的更多信息: https ://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.