Domanda

Context:

I've the following table(Example):

| ID  |   name   | COUNTRY                  |
---------------------------------------------
| 1   | cristian | FRANCIA,HOLANDA,ALEMANIA |
| 2   | Andrea   | FRANCIA,ESPAÑA,BELGICA   |
| 3   | Fabian   | BELGICA,ALEMANIA         |

I need to put all countries in a field, but I need that there aren't repeat values.

So, I'm trygin the following query:

select GROUP_CONCAT(DISTINCT(COUNTRY)) FROM  Usuario;

or using regular expresion Some like :

select GROUP_CONCAT(DISTINCT(COUNTRY)) FROM  Usuario
WHERE GROUP_CONCAT(COUNTRY) REGEXP 'somepattern'

The wrong answer is the next:

FRANCIA,HOLANDA,ALEMANIA,FRANCIA,ESPAÑA,BELGICA,BELGICA,ALEMANIA

The expected answer is:

FRANCIA,HOLANDA,ALEMANIA,ESPAÑA,BELGICA

Or make a some stored procedure?

How to get the expected answer, to N values and differing values?

Thanks for your knowledge and Time!.

È stato utile?

Soluzione

There's no builtin function to do this in MySQL.

It's possible to do a boatload of string processing in MySQL, but it's ugly, and there has to be known finite limit on the number of string values in the comma separated list.

Here's one way to get a distinct list of field values from all those comma separated lists:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(country,','),',',1),',',-1) AS fld
  FROM mytable
HAVING fld <> ''
 UNION
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(country,','),',',2),',',-1) AS fld
  FROM mytable
HAVING fld <> ''
 UNION
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(country,','),',',3),',',-1) AS fld
  FROM mytable
HAVING fld <> ''
 UNION
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(country,','),',',4),',',-1) AS fld
  FROM mytable
HAVING fld <> ''
 UNION
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(country,','),',',5),',',-1) AS fld
  FROM mytable
HAVING fld <> ''
 UNION
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(country,','),',',6),',',-1) AS fld
  FROM mytable
HAVING fld <> ''
 ORDER BY 1

I'll leave it as an exercise for you to figure out what that's doing and how it works.

Now that's each value is in a separate row, we'd think you might want to leave it that way.

It's easy to wrap that query in another query, and use a GROUP_CONCAT function, and return a single row with a string value containing a comma separated list.

Altri suggerimenti

No way with mysql for getting unique like this way.

First it's bad that you storing values like this way.

you have two solution:

1- Normalize your database.

2-get values from table and use php explode() , and use array_unique to remove duplicate values.

Initially you have to create new lookup tables which contains country name per row (Here COUNTRY_TABLE). Then try this.

SELECT (SELECT GROUP_CONCAT(DISTINCT c.COUNTRYNAME) FROM  COUNTRY_TABLE AS c WHERE  FIND_IN_SET(c.COUNTRYNAME,COUNTRY) ) AS UNIQUECOUNTRYNAMES FROM Usuario;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top