加入父母和子女ID

时间:2013-01-21 14:31:57

标签: mysql sql select join

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

+-------------+------------------+------+-----+---------+----------------+
| 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

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

例如,如果name字段为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);

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

在这里:我不知道如何在sql小提琴上保存和链接 - 但这里是代码:

create table loca (
   locaid int,
   locaname varchar(25),
   locaparent varchar(25));

create table cityb (
  citybid int,
  citybname varchar(25),
  citybstate varchar(25));

insert into loca (locaid, locaname, locaparent)
  values (1, 'name1', 'parent1');
insert into loca (locaid, locaname, locaparent)
  values (2, 'name2', 'parent2');
insert into loca (locaid, locaname, locaparent)
  values (3, 'name3', 'parent3');
insert into cityb (citybid, citybname, citybstate)
  values (1, 'city1', '');
insert into cityb (citybid, citybname, citybstate)
  values (2, 'city2', '');
insert into cityb (citybid, citybname, citybstate)
  values (3, 'city3', '');

update loca, cityb
    set citybstate = locaparent
      where locaid = citybid;