Remove duplicate words from field in mysql

后端 未结 6 507
囚心锁ツ
囚心锁ツ 2021-01-21 03:02

I am wondering if it is possible to remove duplicate text using a mysql query from one field, or if a problem like this would be better solved using PHP.

I have a databa

6条回答
  •  盖世英雄少女心
    2021-01-21 03:20

    If it's a real option,

    Change your database design. I don't know about your time constraints so it may really not be an option, but consider which of these two paths you'd rather go down:

    • A couple of hours now redesigning the database, then writing, debugging and verifying a script that'll take all the values from the existing layout and put them in the new one.
    • Hours and hours later coming up with obscure queries for otherwise simple tasks that would take ten minutes to write a query for if the database was designed the way a relational database should be.

    If it's really not an option though...

    Let Sentence = the string of words.
    Split Sentence up on every space and build an array out of it*. Store this as Words.
    Let UniqueWords = an array of words with no duplicates.
    For each Word in Words:
         If the Word is not in UniqueWords, put it in.
    

    *a la PHP explode

    You could also process it as a raw string (stopping to check at spaces or EOL), which may be faster, but if speed is important, your current database design should be far more concerning than this loop.

    EDIT: I didn't see that you wanted it in a SQL query. I'm not sure it'd be possible using a query; perhaps a stored procedure will do. I don't know how to use those though.

提交回复
热议问题