[英]How to Update a MySQL Table Based on SELECT MAX() from a JOINED Table
I have 2 MySQL Tables. 我有2个MySQL表。
TableA
ID Total
01 0
02 0
03 0
...
99 0
TableB
ID Name Points Year
01 Joe 4 2013
01 Bill 2 2013
02 Sam 10 2013
02 Barb 1 2013
02 Joan 7 2013
...
15 Fred 0 2013
15 Jan 3 2013
...
I want to store the MAX(Points)
value from Table B
based on ID
in the Total
column in Table A
我想根据
Table A
Total
列中的ID
存储Table B
的MAX(Points)
值
I have a MySQL Query that gets me the MAX(Points)
. 我有一个MySQL查询,可以获得
MAX(Points)
。 Rather than coding a separate UPDATE
query while looping through the results set from my MAX()
query, I am wondering if I can accomplish this all in one MySQL query using a Join and a SET SELECT
of some sort. 而不是在从我的
MAX()
查询循环遍历结果集时编写单独的UPDATE
查询,我想知道我是否可以使用某种类型的Join和SET SELECT
在一个MySQL查询中完成所有这些。
Is this possible to consolidate the 2 queries into 1? 这可以将2个查询合并为1吗?
Here is my MAX() Query: 这是我的MAX()查询:
$result = mysql_query('
SELECT id, MAX(Points)
FROM TableB
WHERE year = "' . date('Y') . '"
GROUP BY id
') or die(mysql_error());
while ($row = mysql_fetch_row($result)) {
mysql_query('
UPDATE TableA
SET Total = "' . $row[1] . '"
WHERE id = "' . $row[0] . '"
') or die(mysql_error());
}
mysql_free_result($result);
Thanks 谢谢
Try using this as your SQL statement: 尝试将此作为您的SQL语句:
UPDATE TableA, TableB
SET TableA.Total = Max(TableB.Points)
WHERE TableA.ID=TableB.ID
AND TableB.year=<whatever>
Take 2 拿2
OK, try this one instead 好的,试试这个
UPDATE tablea
JOIN (
SELECT id, max(points) AS total
FROM tableb
WHERE year=<whatever>
GROUP BY id
) AS sub ON tablea.id=sub.id
SET tablea.total=sub.total
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.