标题没有正确描述我的问题,但我不知道怎么回事呢..
我试着在这里解释得更好......
我不太喜欢使用mysql所以请在解释时记住这一点:P
我有一个名为'person'的表,如下所示:
id name country father_id
52 bob NULL 68
68 joe Maui 72
53 mia NULL 68
51 robbie NULL 68
我现在想直接在数据库中运行一个查询来更新所有person.id,并使用与其father_id相同的国家/地区
因此人员表将如下所示:
id name country father_id
52 bob Maui 68
68 joe Maui 72
53 mia Maui 68
51 robbie Maui 68
所以我的问题是如何根据person.id的father_id的国家进行更新... phew:P
希望有人可以帮助我:D
答案 0 :(得分:1)
您可以使用update
语句和相关子查询执行此操作:
update person
set country = (select country from person p2 where person.father_id = p2.id)
where father_id is not null;
编辑:
我试图保持简单,忘记MySQL需要额外的子查询层,然后这些不适用于关联。以上是MySQL不支持的标准SQL。
所以在这种情况下你必须使用join
:
update person p join
person father
on p.father_id = father.id
set p.country = father.country;
答案 1 :(得分:0)
试试这个,我是一个神谕,但它是主要的想法
update person p1 set p1.country = (select (country) from person p2 where p2.id = p1.father_id)