1

I want export data from my SQL database. Simply use :

SELECT `id`,`tags` FROM `posts`

This query give me those results :

    (1, 'handshake,ssl,windows'),
    (2, 'office,word,windows'),
    (3, 'site')

I want results in this form:

    (1, 'handshake'),
    (1, 'ssl'),
    (1, 'windows'),
    (2, 'office'),
    (2, 'word'),
    (2, 'windows'),
    (3, 'site')

How can write a query that give me this results? Thank you and sorry for my poor English.

PCcloob.Ir
  • 87
  • 12
  • 1
    Which DBMS are you using? Please add the correct tag: sql-server, mysql, oracle, ... – Hans Kesting Dec 19 '22 at 11:04
  • 3
    If your are interested in separate tags, you should store the tags separately. As is, your table is not normalized; it violates the first normal form, because you store many tags in the same string. Get the database straight, rather then looking for ways to muddle through with it. – Thorsten Kettner Dec 19 '22 at 11:15

3 Answers3

2

If you are using SQL Server You can apply the fuction

STRING_SPLIT

SELECT id, value
FROM posts
CROSS APPLY STRING_SPLIT(tags, ',')

Check this out: SQL Fiddle example

Dúver Cruz
  • 328
  • 1
  • 12
0

After many search and try finally i find the solution:

 SELECT
   DISTINCT postid , SUBSTRING_INDEX(SUBSTRING_INDEX(tags, ',', n.digit+1), ',', -1) val
FROM
  posts
  INNER JOIN
  (SELECT 0 digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3  UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6) n
  ON LENGTH(REPLACE(tags, ',' , '')) <= LENGTH(tags)-n.digit;
PCcloob.Ir
  • 87
  • 12
0

For a max of three words, the code below can be used. If you want more words then you just add more lines. The method may not be fully automated, but it works.

SELECT id, SUBSTRING_INDEX(SUBSTRING_INDEX(tags, ',', 1), ',', -1) FROM tabela 
            UNION
    SELECT id, SUBSTRING_INDEX(SUBSTRING_INDEX(tags, ',', 2), ',', -1) FROM tabela 
            UNION
    SELECT id, SUBSTRING_INDEX(SUBSTRING_INDEX(tags, ',', 3), ',', -1) FROM tabela
    ORDER BY id;
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 21 '22 at 23:09