我有以下查询可以正常工作,但我不明白为什么。我正在更改每一行的余额列。它如何知道要为特定客户更新哪一行。
UPDATE phppos_customers SET balance =
IFNULL((SELECT SUM(transaction_amount)
FROM `phppos_store_accounts`
WHERE deleted = 0 and customer_id = phppos_customers.person_id), 0);
最佳答案
为了举例,假设您有以下两个表
[Users]
+---------+----------+
| user_id | username |
+---------+----------+
| 1 | patrick |
| 2 | chris |
+---------+----------+
[Names]
+---------+------------+-----------+
| user_id | first_name | last_name |
+---------+------------+-----------+
| 1 | Patrick | Stewart |
| 2 | Chris | Angel |
+---------+------------+-----------+
如果您有一个与原始帖子中类似的更新查询,您会想要告诉它如何对齐两个表。如果您有 WHERE Users.user_id = Names.user_id 子句,您实际上是在告诉 SQL 查看数据,就像两个表并排对齐一样,使用两个表中的 user_id 来确定它们匹配的位置。这意味着 user_id 1 的 [Names] 表中的 first_name 和 last_name 将在更新 [Users] 表中 user_id 1 的行时使用。它本质上是查看合并在一起的数据,如下所示:
[Users] and [Names] tables aligned by the user_id columns
+---------+----------+---------+------------+-----------+
| user_id | username | user_id | first_name | last_name |
+---------+----------+---------+------------+-----------+
| 1 | patrick | 1 | Patrick | Stewart |
| 2 | chris | 2 | Chris | Angel |
+---------+----------+---------+------------+-----------+
因此,当 SQL 进行更新时,它会使用另一个表中的相应数据更新每一行,使用这种对齐方式来了解每一行更新要使用哪些数据。
对齐/合并来自多个表的数据的过程在 SQL 中称为连接,这里还有一些information that illustrates how it works如果你有兴趣。
关于mysql - 使用 select 更新查询——它如何知道要更新哪一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24523131/