简体   繁体   中英

join and left join same table

i have tables:

ppls

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

cats

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

i need result:

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

query:

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'

not work properly. how to fix?

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

Try this:

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

So, you get at the result you want using conditional aggregation and a single join operation to the cats table.

Demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM