从3个不同的表中更新字段

时间:2012-11-12 07:32:26

标签: sql

我有一个使用以下3个表的问题:

1. Company (table)
CONAME
COPOINTS

2. Group_Member (table)
CONAME
NAME

3. Member (table)
NAME
MPOINTS

我希望在以下条件下获得正确的查询:

Update Member
Set MPOINTS=MPOINTS+5
Where Company.CONAME=Group_Member.CONAME
And
Group_Member.NAME=Member.NAME

请您更正以上查询?

3 个答案:

答案 0 :(得分:1)

在T-SQL(MS-SQL Server方言)中,这将是

Update Member
   set MPOINTS = MPOINTS + 5
  from Group_Member 
       join Company on Company.CONAME = Group_Member.CONAME
 where Group_Member.NAME = Member.NAME

我想提醒您,对于主要和外国关系,这些名称不是一个好的选择。在不违反主键约束的情况下,您永远无法更改名称。改为使用(数字,自动增量)ID列。

答案 1 :(得分:0)

试试这个:

Update M
Set    MPOINTS=MPOINTS+5
from   Member M 
join   Group_Member GM
on     GM.NAME=M.NAME
join   Company C
on     C.CONAME=GM.CONAME

答案 2 :(得分:0)

SQL Server 2005 +

UPDATE x
SET x.MPOINTS += 5
FROM (SELECT m.MPOINTS FROM Company c JOIN Group_Member g ON c.CONAME = g.CONAME
                                      JOIN Member m ON g.NAME = m.NAME) x