加入并离开加入同一个表

时间:2016-01-29 19:59:44

标签: sql postgresql

我有桌子:

PPLS

pid | name
----+-----
 1  | test1
 2  | test2

cid | cname | cval
----+-------+-----
 1  | cat1  | ctest1-1
 2  | cat2  | ctest1-2
 3  | cat1  | ctest2-1
 4  | cat2  | ctest2-2

ppls_cats

pid | cid 
----+----
  1 | 1
  1 | 2
  2 | 3
  2 | 4

我需要结果:

name  |   cat1   |   cat2 
------+----------+---------
test1 | ctest1-1 | ctest1-2
test2 | ctest2-1 | ctest2-2

查询:

select name, c1.cval as cat1, c2.cval as cat2 from ppls p
join ppls_cats pc on p.pid=pc.pid
left join cats c1 on pc.cid=c1.cid and c1.cname='cat1'
left join cats c2 on pc.cid=c2.cid and c2.cname='cat2'

无法正常工作。如何解决?

ps:http://sqlfiddle.com/#!9/f0ec5/1

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT t1.name, 
       MAX(CASE WHEN t3.cname = 'cat1' THEN cval END) AS cat1,
       MAX(CASE WHEN t3.cname = 'cat2' THEN cval END) AS cat2
FROM ppls AS t1
LEFT JOIN ppls_cats AS t2 ON t1.pid = t2.pid
LEFT JOIN cats AS t3 ON t2.cid = t3.cid
GROUP BY t1.pid, t1.name

因此,您可以使用条件聚合连接操作获得您想要的结果{/ 1}}表。

Demo here