2017-02-14 11 views
0

私はクライアント用の小さなディレクトリのWebサイトをセットアップしました。我々は、少なくともこれら2知っておく必要があります。この問題についてはSQLのテーブル結合から重複を削除するには

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 

を...私はもっとこの

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

...ではなく、このような何か(のようなものを取得したいですそれは結合です)

| 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  |  

純粋なSQLと上記のような別のタグをマージすることは可能ですか?

答えて

2

テーブルを結合した後にはGROUP_CONCATが必要です。

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 
1

あなただけgroup bygroup_concat()をしたいです。あなたはplacesからすべての列をしたいので、しかし、私は、サブクエリを使用します。

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

使用内部結合

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

関連する問題