1

想象一下,你有一个这样的表:

+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(11)          | NO   | PRI | NULL    | auto_increment |
| name        | varchar(255)     | NO   |     |         |                |
| parent_id   | int(11)          | YES  | MUL | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+

让我们称这个表locations

这代表一个城市或一个州。

例如,如果namefield 是Los Angeles,它的 parent_id 将表示带有name字段的行California

现在想象你有另一个这样的表:

+-----------------+---------------+------+-----+---------+----------------+
| Field           | Type          | Null | Key | Default | Extra          |
+-----------------+---------------+------+-----+---------+----------------+
| id              | int(11)       | NO   | PRI | NULL    | auto_increment |
| name            | varchar(450)  | YES  |     | NULL    |                |
| state           | varchar(135)  | YES  |     | NULL    |                |
+-----------------+---------------+------+-----+---------+----------------+

我们称这张桌子为cities

每行代表一个城市,id字段与表id中的匹配locations

在此表中,该state字段始终为空,因此我想使用表中的name字段对其进行更新locations

我已经尝试过此查询以获取该state值,但它似乎不起作用(需要很长时间并且没有任何反应):

SELECT name FROM locations WHERE id IN 
(SELECT parent_gid FROM locations INNER JOIN cities  
ON locations.id = cities.id);

关于如何实现这一目标的任何建议?

4

2 回答 2

1

给你:我不知道如何在 sql fiddle 上保存和链接它 - 但这是代码:

创建表位置 (
   定位整数,
   本地名称 varchar(25),
   局部变量 varchar(25));

创建表 cityb (
  citybid int,
  城市名称 varchar(25),
  citybstate varchar(25));

插入 loca (locaid, locaname, locaparent)
  值(1,'name1','parent1');
插入 loca (locaid, locaname, locaparent)
  值(2,'name2','parent2');
插入 loca (locaid, locaname, locaparent)
  值(3,'name3','parent3');
插入cityb(citybid、citybname、citybstate)
  值(1,'city1','');
插入cityb(citybid、citybname、citybstate)
  值(2,'city2','');
插入cityb(citybid、citybname、citybstate)
  值(3,'city3','');

更新地点,城市b
    设置 citybstate = locaparent
      其中 locaid = citybid;
于 2013-01-21T15:21:06.037 回答
1

如果只需要SELECT声明,请使用JOIN

SELECT  a.id, a.name, b.name As State
FROM    cities a
        INNER JOIN locations b
            ON a.id = b.id

但如果你想更新表格,

UPDATE  cities a
        INNER JOIN locations b
            On a.ID = b.ID
SET     a.State = b.name

更新

SELECT  a.id, a.name, c.name As State
FROM    cities a
        INNER JOIN locations b
            ON a.id = b.id
        LEFT JOIN locations c
            On b.parent_ID = c.id
于 2013-01-21T14:35:29.010 回答