我需要对2表连接的结果进行更新查询。这两个表是n:n关系。这是表格:
表1:
*CITIES* [this is the table name]
idcities (primary key)
cityname
关系标签:
*USER_HAS_CITIES* [this is the table name]
user_iduser (foreign key)
cities_idcities (foreign key)
表2:
*USER* [this is the table name]
iduser (primary key)
username
password
name
surname
例如,我需要更新" cityname" (设置为洛杉矶)user.iduser = 1 and cities.idcities = 2;
我该怎么做?
答案 0 :(得分:1)
在MS SQL中:
UPDATE c
SET c.cityname = 'Los Angeles'
FROM CITIES c
INNER JOIN USER_HAS_CITIES u ON u.ities_idcities = c.idcities
WHERE c.idcities = 2 AND u.iduser = 1
在MySQL中:
UPDATE CITIES c
INNER JOIN USER_HAS_CITIES u ON u.ities_idcities = c.idcities AND c.idcities = 2 AND u.iduser = 1
SET c.cityname = 'Los Angeles'
答案 1 :(得分:1)
问题不是很清楚,但是我们有一个全新的堆栈溢出成员问它,所以我会尝试做一些假设,看看我是否可以引导他们答案。
首先,如果您有cities
表,更新城市名称没有多大意义。只需根据需要添加或删除列表中的记录。如果您必须更新名称,则不会加入。简单地:
update cities set cityname = 'Los Angeles' where id = 2;
users
表也是如此。不要使用联接,只需:
update users set pwd = '1234' where id = 4;
唯一值得更新此问题的表是user_has_cities
表。
因此,让我们假设您的user_has_cities
表格有很多:很多关系,即有很多用户,每个用户都有很多城市,如下例所示:http://sqlfiddle.com/#!9/f146b
如果您知道城市和用户的ID,则可以进行简单的更新:http://sqlfiddle.com/#!9/8a420/1
update user_has_cities
set idcities = 1
where iduser = 5
and idcities = 6;
如果您不知道城市的ID,只知道名称,您可以在select
条款中添加set
,如下所示:http://sqlfiddle.com/#!9/0b1f3/1
update user_has_cities
set idcities = (
select id from cities where cityname = 'Los Angeles' limit 1
)
where iduser = 5
and idcities = 6;
确保限制所返回的记录,否则如果多个城市的名称为“洛杉矶”,您将收到错误消息。无论如何,这是非常粗略的代码;使用唯一ID进行更新会更好。
如果您不知道当前城市的ID,理论上您可以扩展这样的主题:http://sqlfiddle.com/#!9/b28876/1
update user_has_cities
set idcities = (
select id from cities where cityname = 'Los Angeles' limit 1
)
where iduser = 5
and idcities in (select id from cities where cityname = 'Huntington Beach');
我没有声称理解这个问题,所以我不知道这是否能解决问题,但我希望这有助于指明你的方向。
答案 2 :(得分:0)
无论您使用哪种DBMS,都可以像这样完成。
update USER_HAS_CITIES
set cities_idcities = (select idcities from CITIES where cityname = 'Los Angeles')
where user_iduser = 1
答案 3 :(得分:0)
由于您实际上建议只更新一个表,因此您不需要任何特殊的酱料:
UPDATE cities
SET cityname = 'Los Angeles'
WHERE idcities = 2
如果您想要更新给定城市是否与给定用户相关,那么您可以为WHERE
子句添加适当的条件:
AND EXISTS(
SELECT 1 FROM user_has_cities WHERE user_iduser = 1 AND cities_idcities = 2)
如果您想根据用户ID更新给定用户的城市名称(-ies),而不知道城市ID,那么您可以这样做:
UPDATE cities
SET cityname = 'Los Angeles'
WHERE idcities IN (
SELECT cities_idcities FROM user_has_cities WHERE user_iduser = 1)