以下是我的表格。
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
知道如何完成这项工作吗?
答案 0 :(得分: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 Here
答案 1 :(得分: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 here http://sqlfiddle.com/#!2/16112/6
答案 2 :(得分: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;
答案 3 :(得分:0)
最好像diEcho建议的那样更改表结构,但对于您的情况,您可以使用下一个查询(数据透视表)。运行此查询,并尝试使用第一个表 -
加入它SELECT
id,
MAX(IF(type = 'phone', value, NULL)) phone,
MAX(IF(type = 'location', value, NULL)) location
FROM
tab2
GROUP BY
id
答案 4 :(得分: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