1

I have table t1 sql records

user_id    tags
  1     <tag1><tag2>
  1     <tag1><tag3>
  2     <tag2><tag3>

I want to divide this records into multiple records and do distinct on it. I want to know how to divide the records based on tags <> into another table t2

I need ouput like this in table t2

user_id    tags
  1     <tag1> 
  1     <tag2>
  1     <tag1>
  1     <tag3>
  2     <tag2>
  2     <tag3>

Can u guys give me some sql query to do??

Ashwin Yaprala
  • 2,737
  • 2
  • 24
  • 56

1 Answers1

0

Try this:

SELECT
    user_id,
    SUBSTRING_INDEX(tags,'<',2) as tag
FROM
    t1
UNION ALL
SELECT
    user_id,
    SUBSTRING_INDEX(tags,'>',-2) as tag
FROM
    t1

UPDATE: for distinct values you can use :

SELECT
    user_id,
    tag
FROM (
    SELECT
        user_id,
        SUBSTRING_INDEX(tags,'<',2) as tag
    FROM
        t1
    UNION ALL
    SELECT
        user_id,
        SUBSTRING_INDEX(tags,'>',-2) as tag
    FROM
        t1
) as tmp
    GROUP BY
        user_id,
        tag
Stephan
  • 8,000
  • 3
  • 36
  • 42
  • 1
    Don't forget to use `SELECT DISTINCT` to remove duplicates if necessary –  May 24 '13 at 07:19
  • given the example of desired output its not needed to remove duplicates, that is why i didn't use `DISTINCT` – Stephan May 24 '13 at 12:35
  • OP's question says "I want to divide this records into multiple records and do distinct on it." –  May 24 '13 at 15:14
  • indeed your right but his output isn't distinct , but i will update the query – Stephan May 24 '13 at 22:34