0

下面是我的桌子。

create table tab1 ( id int, myname varchar(20));

insert into tab1 values 
(1, 'name 1'),
(2, 'name 2');

create table tab2 ( id int, tab2id int, type varchar(20), value varchar(20));
insert into tab2 values
(1,1,'phone','12345671'),
(1,2,'location','location 1'),
(2,3,'phone','12345672'),
(2,4,'location','location 2');

我想要的是如下。

myname   |   phone    | location  
 name 1  |  12345671  | location 1
 name 2  |  12345672  | location 2

知道如何完成这项工作吗?

用于检查查询的虚拟数据

4

5 回答 5

1
select x.myname as name, a.value as Phone, b.value as Location
from tab1 x,
(select value, id
from tab2 
where type='phone' 
group by id)a,
(select value, id
from tab2 
where type='location' 
group by id)b
where x.id = a.id
and x.id = b.id;

SQL FIDDLE在这里

于 2012-10-10T08:40:58.447 回答
0
select t1.myname,t2.value as phone,t3.value as location from tab1 t1 
inner join tab2 t2 on t1.id=t2.id and t2.type='phone' 
inner join tab2 t3 on t1.id=t3.id and t3.type='location' 

SQL FIDDLE在这里 http://sqlfiddle.com/#!2/16112/6

于 2012-10-10T08:23:22.820 回答
0

没关系,我已经离开这里了......

试试这个:

select tab1.id, tab1.myname, tab2.type, tab2.value from tab1 join tab2 on tab1.id=tab2.id 
JOIN tab2 as t2 ON tab1.id=tab2.id WHERE t2.tab2id=2;

http://sqlfiddle.com/#!2/80d02/7

于 2012-10-10T08:23:50.647 回答
0

最好按照 diEcho 的建议更改表结构,但对于您的情况,您可以使用下一个查询(数据透视表)。运行此查询,并尝试将其与第一个表连接 -

SELECT
  id,
  MAX(IF(type = 'phone', value, NULL)) phone,
  MAX(IF(type = 'location', value, NULL)) location
FROM
  tab2
GROUP BY
  id
于 2012-10-10T08:35:19.573 回答
0

试试这个:

select * from 
(select (select myname from tab1 where id=t1.id) myname,CASE WHEN t1.type='phone' then t1.value end as 'Phone', (select value from tab2 where id=t1.id and type='location') 'Location'
from tab2 t1) a where phone is not null 

SQL 小提琴演示

于 2012-10-10T08:46:11.500 回答