2012-06-28 59 views
0

我有三個表格:upload,tag和upload_tag。上傳保存文件上傳的細節,標籤持有標記名稱和upload_tag是一個查找表,它匹配的上傳ID,以標籤ID即:如何連接來自MYSQL中查找表的字符串值

+--------------------------------------------------------+ 
| upload             | 
+--------------------------------------------------------+ 
|id   |name          | 
+-----------+--------------------------------------------+ 
|1   |file_1.jpg         | 
+-----------+--------------------------------------------+ 
|2   |file_2.doc         | 
+-----------+--------------------------------------------+ 

+--------------------------------------------------------+ 
|tag              | 
+--------------------------------------------------------+ 
|id   |name          | 
+-----------+--------------------------------------------+ 
|1   |a_tag          | 
+-----------+--------------------------------------------+ 
|2   |b_tag          | 
+-----------+--------------------------------------------+ 
|3   |c_tag          | 
+-----------+--------------------------------------------+ 

+--------------------------------------------------------+ 
|upload_tag            | 
+-----------+--------------------------------------------+ 
|upload_id |tag_id          | 
+-----------+--------------------------------------------+ 
|1   |1           | 
+-----------+--------------------------------------------+ 
|1   |2           | 
+-----------+--------------------------------------------+ 
|2   |3           | 
+-----------+--------------------------------------------+ 
|2   |2           | 
+-----------+--------------------------------------------+ 

我需要從標籤的字符串的數據庫中提取上傳,但所有在一排這樣的結果會是這樣的:

+----------------------------------------------------+ 
|filename  |tags         | 
+--------------+-------------------------------------+ 
|file_1.jpg |a_tag; b_tag       | 
+--------------+-------------------------------------+ 
|file_2.doc |c_tag; b_tag       | 
+--------------+-------------------------------------+ 

目前,我在想,要做到這一點,最好的辦法是建立一個MySQL的函數,它接受的上傳ID,並返回標籤的格式化字符串。我在這裏糾正,還是有更好的方法來實現這一目標?

+0

可能重複[如何從MySQL SELECT串聯值(http://stackoverflow.com/questions/1091746/how-to-concatenate-values-from-mysql - 選擇) – Ken

+0

@Ken:這有點類似但是不重複... –

回答

2

您應該使用LEFT JOIN子句和GROUP_CONCAT()函數。

SELECT   u.name AS filename, 
       GROUP_CONCAT(t.name SEPARATOR '; ') AS tags 
    FROM  upload u 
    LEFT JOIN upload_tags ut 
     ON  u.id = ut.upload_id 
    LEFT JOIN tag t 
     ON  t.id = ut.tag_id 
    GROUP BY u.id; 

GROUP_CONCAT是一個聚集函數,這意味着它可以在多行(組織爲基),而不是其CONCAT在多個列上的工作原理。

1

試試這個::

select 
upload.name as filename 
GROUP_CONCAT(tag.name SEPARATOR '; ') as tags 
from 
upload_tag ut 
inner join upload on (ut.upload_id = upload.id) 
inner join tags on (ut.tag_id = tags.id) 
group by ut.upload_id 
+0

'INNER JOIN' with upload_tag作爲基表只會獲取那些有標籤的文件名。有理由說,即使它們沒有任何關聯的標記,也要使用文件名。 –

相關問題