ID                   TYPE                 NAME                      PARENT_ID
1                    country              中国                      
2                    province             广东                      1
3                    city                 广州                      2我想要效果:type                   name                   parent
country                中国
province               广东                   中国
city                   广州                   广东怎样用一条sql语句实现?

解决方案 »

  1.   

    select  a.type , a.name, b.name from 表 as a left join 表 as b on  b.id=a.PARENT_ID  
      

  2.   

    没有什么其它好办法了。 
    用left join 应该已经是最好的方法了。
    只不过是同一个表的两个别名,其它在数据库查询中经常会有这种现象。
      

  3.   

    thx
    但是用这种最上级没有parentId的不能查询出来,怎么解决呢?
      

  4.   


    不会啊,1楼已经用的是 left join 了,即使  最上级没有parentId 应该也会查出。贴出你的语句和试验结果。
      

  5.   

    1楼的完全符合您的要求阿!mysql> select * from tg1;
    +----+----------+------+-----------+
    | id | type     | name | parent_id |
    +----+----------+------+-----------+
    |  1 | country  | 中国 |      NULL |
    |  2 | province | 广东 |         1 |
    |  3 | city     | 广州 |         2 |
    +----+----------+------+-----------+
    3 rows in set (0.03 sec)mysql> select t1.type,t1.name,t2.name from tg1 as t1 left join tg1 as t2 on t1.p
    arent_id=t2.id;
    +----------+------+------+
    | type     | name | name |
    +----------+------+------+
    | country  | 中国 | NULL |
    | province | 广东 | 中国 |
    | city     | 广州 | 广东 |
    +----------+------+------+
    3 rows in set (0.00 sec)mysql> desc tg1;
    +-----------+-------------+------+-----+---------+----------------+
    | Field     | Type        | Null | Key | Default | Extra          |
    +-----------+-------------+------+-----+---------+----------------+
    | id        | bigint(20)  | NO   | PRI | NULL    | auto_increment |
    | type      | varchar(10) | NO   |     |         |                |
    | name      | varchar(20) | NO   |     |         |                |
    | parent_id | int(11)     | YES  |     | NULL    |                |
    +-----------+-------------+------+-----+---------+----------------+
    4 rows in set (0.03 sec)
      

  6.   

    mysql> select t1.type,t1.name,t2.name as parent from tg1 as t1 left join tg1 as
    t2 on t1.parent_id=t2.id;
    +----------+------+--------+
    | type     | name | parent |
    +----------+------+--------+
    | country  | 中国 | NULL   |
    | province | 广东 | 中国   |
    | city     | 广州 | 广东   |
    +----------+------+--------+
    3 rows in set (0.00 sec)