我有两个这样的表:
// users
+----+--------+----------------------------+------------------+
| id | name | email | notification_num |
+----+--------+----------------------------+------------------+
| 1 | John | John134@gmail.com | 4 |
| 2 | Peter | matrix_peter@ymail.com | 2 |
| 3 | Jack | jk_43m@gmail.com | 6 |
+----+--------+----------------------------+------------------+
// notifications
+----+---------+---------+------+
| id | post_id | user_id | seen |
+----+---------+---------+------+
| 1 | 4325 | 2 | NULL |
| 2 | 8765 | 3 | NULL |
| 3 | 5454 | 3 | 1 |
| 4 | 4346 | 2 | NULL |
| 5 | 3243 | 1 | 1 |
| 6 | 3246 | 2 | 1 |
| 7 | 3764 | 3 | 1 |
+----+---------+---------+------+
好的,我只有一个 user_id。例如 :user_id = 2
,然后我想要这样的输出:
// users
+----+--------+----------------------------+------------------+
| id | name | email | notification_num |
+----+--------+----------------------------+------------------+
| 1 | John | John134@gmail.com | 4 |
| 2 | Peter | matrix_peter@ymail.com | 0 |
| 3 | Jack | jk_43m@gmail.com | 6 |
+----+--------+----------------------------+------------------+
// notifications
+----+---------+---------+------+
| id | post_id | user_id | seen |
+----+---------+---------+------+
| 1 | 4325 | 2 | 1 |
| 2 | 8765 | 3 | NULL |
| 3 | 5454 | 3 | 1 |
| 4 | 4346 | 2 | 1 |
| 5 | 3243 | 1 | 1 |
| 6 | 3246 | 2 | 1 |
| 7 | 3764 | 3 | 1 |
+----+---------+---------+------+
如您所见,我想更新 users.cotification_num
并将其设置为 0
(对于这样的用户),我也想要更新 notifications.seen
并将所有行设置为 1
(对于这样的用户)。我该怎么做?
我可以通过两个不同的查询来做到这一点:
UPDATE users SET notification_num = 0 WHERE id = :user_id
UPDATE notifications SET seen = 1 WHERE seen is NULL and user_id = :user_id
但我想知道如何通过一个查询来做到这一点?
最佳答案
您可以使用多表 UPDATE
:
UPDATE users u LEFT JOIN notifications n ON n.user_id = u.id
SET u.notification_num = 0,
n.seen = 1
WHERE u.id = 2
关于mysql - 如何在一个查询中更新两个不同的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39216404/