简体   繁体   中英

How to remove duplicates from table join in SQL

I have set up a little directory website for client.

For this question we need to know at least those two:

   TABLE: places                       TABLE: tags

   | pid | name    | lat  | lng  |     | tid | pid | value |
   -------------------------------     ---------------------
   |  1  | Place 1 | x.xx | x.xx |     |  0  |  2  | tag1
   |  2  | Place 2 | x.xx | x.xx |  +  |  1  |  2  | tag2
   |  3  | Place 3 | x.xx | x.xx |     |  2  |  1  | tag1

... I want to get something more like this

   | pid | name    | lat  | lng  | value      |
   --------------------------------------------
   |  2  | Place 2 | x.xx | x.xx | tag1, tag2 | <3    
   |  1  | Place 1 | x.xx | x.xx | tag1       |  

... and not something like this (thats a join)

   | pid | name    | lat  | lng  | value      |
   --------------------------------------------
   |  2  | Place 2 | x.xx | x.xx | tag1       | 
   |  2  | Place 2 | x.xx | x.xx | tag2       |              
   |  1  | Place 1 | x.xx | x.xx | tag1       |     

Is it possible to merge different tags like above with pure SQL?

You just need GROUP_CONCAT after joining the tables.

select p.pid,p.name,p.lat,p.long,group_concat(t.value) as value
from places p
join tags t on p.pid=t.pid
group by p.pid,p.name,p.lat,p.long

You just want group by and group_concat() . However, because you want all the columns from places I would use a subquery:

select p.*,
       (select group_concat(t.value)
        from tags t
        where t.pid = p.pid
       ) as `values`
from places p;

使用内部联接

select p.pid,p.name,p.lat,p.long,group_concat(t.value) as value from places p inner join tags t on p.pid=t.pid group by p.pid,p.name,p.lat,p.long

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