简体   繁体   中英

Select distinct values from table

I have a table where I stored my blog articles, The structure is like this :

id,title,description,tags..

In the tags column the data is stored like this : tag1,tag2,tag3,tag4.

I want to select all distinct tags from all my articles

ex:
article 1 :tags1,tags2,tags3,tags,4
article 2 : tags 1,tags4,tag5,tags 6

After query :
tags1,tag2,tags3,tags4,tags5,tags6

How can I do this ?

This ugly query will work for a maximum of 8 tags in one article but you can add more SELECT UNION if needed.

Since you didn't provide the table name I guessed "Article".

SELECT
  DISTINCT(Tags)
FROM
(SELECT TRIM(SUBSTRING_INDEX(Article.Tags, ',', 1)) AS Tags FROM Article UNION
 SELECT TRIM(SUBSTRING(SUBSTRING_INDEX(Article.Tags, ',', 2), LENGTH(SUBSTRING_INDEX(Article.Tags, ',', 1))+2)) FROM Article UNION
 SELECT TRIM(SUBSTRING(SUBSTRING_INDEX(Article.Tags, ',', 3), LENGTH(SUBSTRING_INDEX(Article.Tags, ',', 2))+2)) FROM Article UNION
 SELECT TRIM(SUBSTRING(SUBSTRING_INDEX(Article.Tags, ',', 4), LENGTH(SUBSTRING_INDEX(Article.Tags, ',', 3))+2)) FROM Article UNION
 SELECT TRIM(SUBSTRING(SUBSTRING_INDEX(Article.Tags, ',', 5), LENGTH(SUBSTRING_INDEX(Article.Tags, ',', 4))+2)) FROM Article UNION
 SELECT TRIM(SUBSTRING(SUBSTRING_INDEX(Article.Tags, ',', 6), LENGTH(SUBSTRING_INDEX(Article.Tags, ',', 5))+2)) FROM Article UNION
 SELECT TRIM(SUBSTRING(SUBSTRING_INDEX(Article.Tags, ',', 7), LENGTH(SUBSTRING_INDEX(Article.Tags, ',', 6))+2)) FROM Article UNION
 SELECT TRIM(SUBSTRING(SUBSTRING_INDEX(Article.Tags, ',', 8), LENGTH(SUBSTRING_INDEX(Article.Tags, ',', 7))+2)) FROM Article
 -- This query will work for a max number of 8 tags in one article : add more SELECT UNION if needed
 )
AS AllTags

As a side note, I totally agree with GolezTrol and you really should consider storing your tags in a separate table.

您应该有一个标签表和一个关联表,在其中存储标签和文章之间的关联。

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