[英]How to remove duplicates from table join in 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合並?
加入表后,只需要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
您只需要group by
和group_concat()
。 但是,由於您希望從places
所有列,因此我將使用子查詢:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.