MySQL - Left Outer Join不更新原始表

时间:2017-04-17 04:49:03

标签: mysql sql

我创建了一个玩具数据集,我试图计算每个用户的帖子数量。我似乎得到了正确的计数值,但用户表中的count列未使用值更新。

我是mysql的新手,非常困惑!有人能告诉我我做错了吗?

 users:
 +---------+------+-------+
| user_id | user | pword |
+---------+------+-------+
|       1 | Amy  | abcd  |
|       2 | Jess | efgh  |
|       3 | Lori | ijkl  |
+---------+------+-------+

posts:
+---------+-------------+------+
| post_id | post        | user |
+---------+-------------+------+
|       1 | hi          | Lori |
|       2 | hello       | Jess |
|       3 | hello again | Jess |
|       4 | and again   | Jess |
+---------+-------------+------+

mysql> ALTER TABLE users ADD COLUMN post_count INT;
mysql> SELECT u.user_id, COUNT(p.user) AS post_count FROM users u LEFT JOIN posts p ON u.user LIKE p.user GROUP BY u.user_id;
+---------+------------+
| user_id | post_count |
+---------+------------+
|       1 |          0 |
|       2 |          3 |
|       3 |          1 |
+---------+------------+

mysql> SELECT * FROM users;
+---------+------+-------+------------+
| user_id | user | pword | post_count |
+---------+------+-------+------------+
|       1 | Amy  | abcd  |       NULL |
|       2 | Jess | efgh  |       NULL |
|       3 | Lori | ijkl  |       NULL |
+---------+------+-------+------------+

谢谢!

2 个答案:

答案 0 :(得分:1)

请尝试以下方法......

UPDATE users
JOIN ( SELECT u.user_id AS user_id,
              COUNT( p.user ) AS post_count
       FROM users u
       LEFT JOIN posts p ON u.user LIKE p.user
       GROUP BY u.user_id ) postCountFinder
    ON users.user_id = postCountFinder.user_id
SET users.post_count = postCountFinder.post_count;

此问题会记录您从以下内容获得的用户和帖子计数...

SELECT u.user_id,
       COUNT( p.user ) AS post_count
FROM users u
LEFT JOIN posts p ON u.user LIKE p.user
GROUP BY u.user_id;

...并对共享值为INNER JOIN的{​​{1}}执行Users,创建一个数据集,其中user_id的每一行都有相应的计数结尾

然后,我们使用users命令将空SETpost_count设置为其对应的连接计数。

如果您有任何问题或意见,请随时发表评论。

答案 1 :(得分:0)

您需要update语句来更新新添加的列中的值。请尝试:

Update usr
set usr.post_count=tbl.post_count
from users usr
inner join
(select  u.user_id,COUNT(p.user) 
AS post_count FROM users u 
LEFT JOIN posts p ON u.user LIKE p.user GROUP BY u.user_id ) tbl
on tbl.user_id=usr.user_id