Table_A
------------
id name
1  Name1
2  Name2Table_B
------------
a_id type   value
1    width  100
1    height 100
2    width  50
2    height 80构造怎样的查询,可以得到:
id  name   width height
1   Name1  100   100
2   Name2  50    80

解决方案 »

  1.   

    基本上就这样
    select tablea.id , tablea.name, tw.value as width, th.value as heightfrom tablea,
    (select * from tableb where type="width") as tw,
    (select * from tableb where type="height") as thwhere
    tablea.id=tw.id and table.id=th.id
      

  2.   

    SELECT A.*,B1.value AS width, B2.value AS heightFROM A
    INNER JOIN B B1 ON A.ID=B1.A_ID AND B1.TYPE='width'
    INNER JOIN B B2 ON A.ID=B2.A_ID AND B1.TYPE='height'
      

  3.   

    select a.id,a.name,b1.type as width,b2.type as height
    from Table_A a inner join Table_B b1 on a.id=b1.id 
    inner join Table_B b2 on a.id=b2.id 
    where b1.type='width'
    and b2.type='height'
      

  4.   

    SELECT A.*,B1.value AS width, B2.value AS height FROM A 
    INNER JOIN B B1 ON A.ID=B1.A_ID AND B1.TYPE='width' 
    INNER JOIN B B2 ON A.ID=B2.A_ID AND B2.TYPE='height'OR
    SELECT A.*,B1.value AS width, B2.value AS height FROM A 
    INNER JOIN B B1 ON A.ID=B1.A_ID 
    INNER JOIN B B2 ON A.ID=B2.A_ID 
    WHERE B1.TYPE='width' AND B2.TYPE='height'
      

  5.   

    似乎就是这种方法了
    事实上Table_B上有更多的type类型按这个方法语句长一点不是问题,就不知道效率怎么样
    当type很多的时候有没有更好的方法?
      

  6.   

    很多种的话,多次JON会需要一些时间。 一般建议用程序或存储过程来实现。在
    http://topic.csdn.net/u/20090530/23/0b782674-4b0b-4cf5-bc1a-e8914aaee5ab.html
    中有一些例子你可以参考一下
      

  7.   

    创建A表
    create table Table_A(
    id int primary key,
    name varchar(10)
    );创建B表
    create table Table_B(
    a_id int references Table_A(id),
    type varchar(10),
    value int
    );插入值:insert into Table_A values(1 ,"Name1"); 
    insert into Table_A values(2 ,"Name2");insert into Table_B values(1,"width",100 );
    insert into Table_B values(1,"height",100 );
    insert into Table_B values(2,"width",50 );
    insert into Table_B values(2,"height",80 );
    查找上述的表:select a.id,a.name,b1.value as width,b2.value as height
    from Table_A a inner join Table_B b1 on a.id=b1.a_id 
        inner join Table_B b2 on a.id=b2.a_id 
    where b1.type='width'
    and b2.type='height';运行结果如下:+----+-------+-------+--------+
    | id | name  | width | height |
    +----+-------+-------+--------+
    |  1 | Name1 |   100 |    100 |
    |  2 | Name2 |    50 |     80 |
    +----+-------+-------+--------+
    2 rows in set (0.00 sec)你可以自己试试!可以结贴了吧!